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

Ari*_*ian 3 c# generics interface c#-4.0

请考虑以下代码:

public interface ImyInterface
{
    T GetEntity<T>(T t,int MasterID);
}
Run Code Online (Sandbox Code Playgroud)

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

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

错误是:

'MyEntity'不包含'A_1'的定义,并且没有可以找到接受类型'MyEntity'的第一个参数的扩展方法'A_1'(您是否缺少using指令或汇编引用?)

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

我的错在哪里?

谢谢


EDIT1)

考虑MyEntity声明是:

public class MyEntity
{
    public string A_1 {set; get;}
}
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 11

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

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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