如何在另一个通用基类上添加C#generics类型约束?

我已多次阅读有关C#generics类型参数约束的MSDN文档,但我无法弄清楚如何执行此操作,或确定它是否可行。

假设我有一个像这样的通用基类:

public abstract class Entity { ... } 

这个抽象基类没有任何类型约束, TId可以是任何东西 – 结构,类等。

现在说我有一个通用的接口方法,我想将方法​​的generics类型约束到上面的类:

 public interface ICommandEntities { void Update(TEntity entity) where TEntity : ?????; } 

我可以这个编译:

 public interface ICommandEntities { void Update(TEntity entity) where TEntity: Entity } 

…然而,我需要在执行方法时显式添加两个T1 ant T2genericsargs:

 commander.Update(abcEntity); 

如果可能的话,我想让编译器推断所有内容,这样我就可以执行这样的方法:

 commander.Update(abcEntity); 

这个活动可能吗? 到目前为止,我能让它工作的唯一方法是在generics基类之上添加一个空的非generics基类,并将其用作方法的类型约束:

 public abstract Entity {} public abstract EntityWithId : Entity { ... } public interface ICommandEntities { void Update(TEntity entity) where TEntity : Entity; } commander.Update(abcEntity); 

…但最终我得到了一个非常无用的类,它充当了标记界面。 这是摆脱这种类型的generics类和接口方法设计的唯一方法吗? 或者我在这里遗漏了什么?

在检查它编译后,我会将其升级为答案。

从您的问题和评论中,您希望参数为Entity 。 您不需要将参数化类型直接用作类型,它可用于参数化参数。

所以就这么做

  public void Update(Entity entity) where .... 

简单的选择是更改ICommandEntities的签名:

 public interface ICommandEntities { void Update(Entity entity) } 

这有效地给出了你所追求的相同约束。

如注释中所述,您应该只创建参数类型BaseClass

 class Program { static void Main( string[] args ) { ITest x = new TestClass(); Console.WriteLine( x.GetTypeArgTypeFrom( new BaseClass() ) ); Console.ReadKey(); } } public class BaseClass { public Type GetTypeArgType() { return typeof( T ); } } public interface ITest { Type GetTypeArgTypeFrom( BaseClass bct ); } public class TestClass : ITest { public Type GetTypeArgTypeFrom( BaseClass bct ) { return bct.GetTypeArgType(); } }