代码之家  ›  专栏  ›  技术社区  ›  Ronald Abellano

泛型类型约束是如何工作的?

  •  3
  • Ronald Abellano  · 技术社区  · 6 年前

    我在研究一般的约束,我碰到了这个,卡住了。我试着用自己的类复制代码,但是我得到了“不一致的不可访问性”。

    //this is the reference study class
    public class MainView<T> : System.Windows.Window where T : INotifyPropertyChanged, new(){}
    
    //my own
    interface ITest{}
    
    class B : ITest
    {
        public B()
        {
    
        }
    }
    
    public class MyClass<T> : B where T : ITest, new()
    {
    
    }
    

    我想不通。参考资料课上有什么?如何对自己定义的类和接口执行相同的签名?

    1 回复  |  直到 6 年前
        1
  •  2
  •   yv989c    6 年前

    注意你的 ITest 接口和 B 类没有显式访问修饰符;如果没有提供,则默认为 internal (对于顶级类型),并在 MyClass public (这比 内部的 ,因此,编译器错误)。解决方案是将类型的访问修饰符改为 在这种情况下,或者,让您的 类名 而不是

     //my own
    public interface ITest{}
    
    public class B : ITest
    {
        public B()
        {
    
        }
    }
    
    public class MyClass<T> : B where T : ITest, new()
    {
    
    }
    

    有关访问修饰符的更多信息,请参见: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels