Tom*_*han 7 c# generics interface reference-type
如果我在C#中声明一个接口,有没有什么办法可以显式地声明实现该接口的任何类型都是引用类型?
我想这样做的原因是,无论我在哪里使用接口作为类型参数,我都不必指定实现类型也必须是引用类型.
我想要完成的例子:
public interface IInterface
{
void A();
int B { get; }
}
public class UsingType<T> where T : IInterface
{
public void DoSomething(T input)
{
SomeClass.AnotherRoutine(input);
}
}
public class SomeClass
{
public static void AnotherRoutine<T>(T input)
where T : class
{
// Do whatever...
}
}
Run Code Online (Sandbox Code Playgroud)
由于参数SomeClass.AnotherRoutine()需要是一个引用类型,我将在这里得到一个编译器错误,我调用该方法,建议我强制T成为引用类型(where T : IInterface, class在声明中UsingType).有没有办法可以在接口级别强制执行此操作?
public interface IInterface : class
Run Code Online (Sandbox Code Playgroud)
不起作用(显然)但也许有另一种方法来完成同样的事情?
| 归档时间: |
|
| 查看次数: |
1317 次 |
| 最近记录: |