加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在泛型(Y)方法中使用泛型(X)委托,其中Y扩展了一些基类.无

发布时间:2020-12-15 23:40:12 所属栏目:百科 来源:网络整理
导读:public abstract class SomeBaseClass {}public class SomeSpecificClass: SomeBaseClass { public int propertyA; public string propertyB;}public delegate void CallbackT(T data);public class Foo { void MethodA T (CallbackT theInstance) where T:
public abstract class SomeBaseClass {}

public class SomeSpecificClass: SomeBaseClass {
    public int propertyA;
    public string propertyB;
}

public delegate void Callback<T>(T data);


public class Foo {


    void MethodA <T> (Callback<T> theInstance) where T: SomeBaseClass {
        MethodB(theInstance);
    }

    void MethodB(Callback<SomeBaseClass> theInstance) {

    }

    void MethodC() {
        Callback<SomeSpecificClass> cb = (data) => {};
        MethodA(cb);
    }

    void MethodD <T> (T theInstance) where T: SomeBaseClass {
        MethodE(theInstance);
    }

    void MethodE (SomeBaseClass theInstance) {

    }
}

在MethodA中产生错误:

参数1:无法从’Callback< T>‘转换’Callback< SomeBaseClass>‘ [汇编CSHARP]
回调< T> theInstance

但MethodD可以很好地将其实例传递给MethodE

为什么我不能通过通用Callback< T> MethodA中的实例,类型为Callback< SomeBaseClass>的参数当我指定T扩展SomeBaseClass的约束时,在MethodB中

解决方法

基本上,你不能这样做,因为它不安全.

假设我们有一个派生自SomeBaseClass的具体类:

public class SomeOtherSpecificClass {}

假设我们将您的MethodB更改为:

void MethodB(Callback<SomeBaseClass> theInstance)
{
    theInstance(new SomeOtherSpecificClass());
}

那应该编译,对吗?毕竟,你只是将SomeOtherSpecificClass传递给Callback< SomeBaseClass>,这应该没问题.

然后,如果我像这样调用MethodA:

Callback<SomeSpecificClass> callbcak = data => Console.WriteLine(data.propertyA);
MethodA(callback);

…然后,如果所有这些都被允许,我们将SomeOtherSpecificClass传递给期望SomeSpecificClass的委托.

您的MethodD和MethodE示例很好,因为MethodE只能使用SomeBaseClass的成员…但是Callback< SomeSpecificClass>确实需要一个SomeSpecificClass,所以你不能把它当作一个接受SomebaseClass的方法来对待它.

为了更简单地展示:

// This is valid...
string text = "";
object obj = text;

// This isn't...
Action<string> stringAction = text => Console.WriteLine(text.Length);
Action<object> objectAction = stringAction;
// ... because it would allow this:
objectAction(new object());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读