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

c# – 在非泛型接口中声明Generic方法

发布时间:2020-12-16 00:11:12 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: public interface ImyInterface{ T GetEntityT(T t,int MasterID);} 我声明了一个类名:MyEntity,它有一个名为A_1的属性 public class BL_Temp : ImyInterface{ public MyEntity GetEntityMyEntity(MyEntity t,int MasterID) { t.A_1 = "";
请考虑以下代码:

public interface ImyInterface
{
    T GetEntity<T>(T t,int MasterID);
}

我声明了一个类名:MyEntity,它有一个名为A_1的属性

public class BL_Temp : ImyInterface
{
    public MyEntity GetEntity<MyEntity>(MyEntity t,int MasterID)
    {
        t.A_1 = ""; //Error
        return t;
    }
}

错误是:

‘MyEntity’ does not contain a definition for ‘A_1’ and no extension method ‘A_1’ accepting a first argument of type ‘MyEntity’ could be found (are you missing a using directive or an assembly reference?)

是否可以在非泛型接口中声明泛型方法?

我的错在哪里?

谢谢

EDIT1)

考虑MyEntity声明是:

public class MyEntity
{
    public string A_1 {set; get;}
}

解决方法

您可以声明,但您的方法将是通用的而不是特定类型.我的意思是MyEntity是通用参数,它不是你的实体类型.

您可以像这样向您的实体添加约束,这允许您访问特定于实体的成员.

public interface ImyInterface
{
    T GetEntity<T>(T t,int MasterID) where T : Entity;
}    

public class BL_Temp : ImyInterface
{
    public T GetEntity<T>(T t,int MasterID) where T : Entity
    {
        t.MyEntityProperty = "";
        return t;
    }
}

我知道这是一个示例代码,但我觉得值得一提的是你的方法不应该撒谎.方法名称是GetEntity,但它改变了客户端可能不知道的参数(我说它撒了谎). IMO你应该至少重命名方法或不改变参数.

(编辑:李大同)

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

    推荐文章
      热点阅读