首页 > 解决方案 > 带有接口参数的 C# 泛型类

问题描述

我尝试创建相同的基本泛型变量并将每个具有继承相同接口的参数的泛型对象分配给它,但我收到错误“无法隐式转换类型”。有人可以帮助我理解这一点吗?

public interface ISomthink
{

}
public class Somethink: ISomthink
{

}
public class Somethink2: ISomthink
{

}
public class MyGeneric<T> where T:ISomthink
{

}
public class Program
{
    public static void Main(string[] args)
    {
        ISomthink s1 = null;
        s1=new Somethink();
        s1 = new Somethink2();

        MyGeneric<ISomthink> sg = null;
        sg=new MyGeneric<Somethink>();//Error Cannot implicitly convert type
        sg = new MyGeneric<Somethink2>();//Error Cannot implicitly convert type

    }
}

标签: c#

解决方案


推荐阅读