C # - Why set a common interface restriction, and not just pass an interface type?

I find a lot of code as follows:

public interface IFoo
{
   void DoSomething();
}

public void RegisterFoos<T>(T foo) where T : IFoo
{
    foo.DoSomething();
}

I do not get such code, why not just pass IFoo?

+4
source share
2 answers

I see at least two reasons.

One reason is to allow the sending of a specific type of link. You can send the same object as an interface, but you can only use foo.GetType()to get the type, but this is the actual type of the object. Using a generic type, you can expose an object to another type, but typeof(T)gets that type.

, , . :

public T DoSomething<T>(T foo) where T : IFoo {
  foo.DoSomething();
  return foo;
}
+3

, .

:

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());
+1

Source: https://habr.com/ru/post/1607117/


All Articles