JSB*_*ոգչ 9 c# generics interface
我的函数的参数f()
必须实现两个不同的接口,这些接口通过继承彼此无关,IFoo
并且IBar
.我知道有两种不同的做法.第一种是声明一个从两者继承的空接口:
public interface IFooBar : IFoo, IBar
{
// nothing to see here
}
public int f(IFooBar arg)
{
// etc.
}
Run Code Online (Sandbox Code Playgroud)
这,当然,要求班宣布自己执行IFooBar
,而不是IFoo
和IBar
独立.
第二种方法是f()
使用约束制作泛型:
public int f<T>(T arg) where T : IFoo, IBar
{
// etc.
}
Run Code Online (Sandbox Code Playgroud)
您更喜欢哪一个,为什么?每个都有任何非明显的优点或缺点吗?
第二种选择更灵活.通过引入一个新接口,您将强制类实现第三个接口,只有当它们具有对您的库(定义接口的地方)的引用时才能实现.
通过使用泛型约束,类只需要对包含IFoo
和的库的引用IBar
,而不是IFooBar
.
归档时间: |
|
查看次数: |
288 次 |
最近记录: |