简体   繁体   English

在泛型类中使用泛型接口

[英]Using generic interface in a generic class

How force to use class that implement generic interface in class?如何强制使用在类中实现泛型接口的类? Is something like this possible?这样的事情可能吗?

public interface IGeneric<T>
{
    T Value {get;}
}

//public class MyList<IGeneric<T>> {}//not allowed

Something like this:像这样的东西:

void Main()
{
    MyList<string> myList = new MyList<string>(new Generic());
}

public interface IGeneric<T>
{
    T Value { get; }
}

public class MyList<T>
{
    private IGeneric<T> _generic;
    public MyList(IGeneric<T> generic)
    {
        _generic = generic;
    }
}

public class Generic : IGeneric<string>
{
    public string Value => throw new NotImplementedException();
}

Or like this:或者像这样:

void Main()
{
    MyList<Generic, string> myList = new MyList<Generic, string>();
    //Or MyList<IGeneric<string>, string> myList = new MyList<IGeneric<string>, string>();
}

public interface IGeneric<T>
{
    T Value { get; }
}

public class MyList<G, T> where G : IGeneric<T>
{
}

public class Generic : IGeneric<string>
{
    public string Value => throw new NotImplementedException();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM