[英]C# - Why put a interface generic constraint instead of just passing the interface type?
我找到了很多像這樣的代碼:
public interface IFoo
{
void DoSomething();
}
public void RegisterFoos<T>(T foo) where T : IFoo
{
foo.DoSomething();
}
我沒有得到這種代碼,為什么不通過IFoo?
我至少可以看到兩個原因。
一個原因是允許發送特定類型的引用。 作為接口,您可以發送相同的對象,但是您只能使用foo.GetType()
來獲取類型,但這是對象的實際類型。 通過使用泛型類型,您可以將對象typeof(T)
轉換為其他類型,並且typeof(T)
獲取該類型。
另一個原因是能夠返回與參數相同類型的引用。 例:
public T DoSomething<T>(T foo) where T : IFoo {
foo.DoSomething();
return foo;
}
通過使用通用約束,您可以更靈活。
考慮:
public class Foo:IFoo
{
public void DoSomething() // from interface
{
}
public void DoSomethingWithFoo() // custom method
{
}
}
現在這個方法的兩個版本:
public void RegisterFoosGeneric<T>(T item, Action<T> action) where T : IFoo
{
action(item);
}
public void RegisterFoos(IFoo item, Action<IFoo> action)
{
action(item);
}
此行有效:
test.RegisterFoosGeneric(new Foo(), x=>x.DoSomethingWithFoo());
這個不是,給出編譯錯誤:
test.RegisterFoos(new Foo1(), x=>x.DoSomethingWithFoo1());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.