How can I use interface as a C# generic type constraint?

前端 未结 11 2220
不思量自难忘°
不思量自难忘° 2020-11-27 12:27

Is there a way to get the following function declaration?

public bool Foo() where T : interface;

ie. where T is an interface type

11条回答
  •  臣服心动
    2020-11-27 12:55

    To follow up on Robert's answer, this is even later, but you can use a static helper class to make the runtime check once only per type:

    public bool Foo() where T : class
    {
        FooHelper.Foo();
    }
    
    private static class FooHelper where TInterface : class
    {
        static FooHelper()
        {
            if (!typeof(TInterface).IsInterface)
                throw // ... some exception
        }
        public static void Foo() { /*...*/ }
    }
    

    I also note that your "should work" solution does not, in fact, work. Consider:

    public bool Foo() where T : IBase;
    public interface IBase { }
    public interface IActual : IBase { string S { get; } }
    public class Actual : IActual { public string S { get; set; } }
    

    Now there's nothing stopping you from calling Foo thus:

    Foo();
    

    The Actual class, after all, satisfies the IBase constraint.

提交回复
热议问题