无法将类型 'app.a1<<string>>' 隐式转换为 'app.a1<<object>>'
Cannot implicitly convert type 'app.a1<<string>>' to 'app.a1<<object>>'
当我尝试编译时,我试图从以下代码中理解泛型和协方差。我收到类似
的错误
Error 1 Cannot implicitly convert type
'ConsoleApplication1.a1<<string>>'
to
'ConsoleApplication1.a1<<object>>'
class a1<T>
{
public void Fmethod( T a)
{
Console.WriteLine(a.GetType().ToString());
}
}
class Program
{
static void Main(string[] args)
{
a1<string> aa1 = new a1<string>();
a1<object> aa2 = new a1<object>();
object b;
aa2.Fmethod(b);
aa1.Fmethod("aa");
aa2 = aa1;
Console.ReadLine();
}
}
根据 docs:
Generic classes are invariant. In other words, if an input parameter specifies a List<BaseClass>
, you will get a compile-time error if you try to provide a List<DerivedClass>
.
应用于您的示例,因为您将 a1<string>
类型的对象分配给 a1<object>
类型的变量,所以会出现错误。
当我尝试编译时,我试图从以下代码中理解泛型和协方差。我收到类似
的错误Error 1 Cannot implicitly convert type
'ConsoleApplication1.a1<<string>>'
to'ConsoleApplication1.a1<<object>>'
class a1<T>
{
public void Fmethod( T a)
{
Console.WriteLine(a.GetType().ToString());
}
}
class Program
{
static void Main(string[] args)
{
a1<string> aa1 = new a1<string>();
a1<object> aa2 = new a1<object>();
object b;
aa2.Fmethod(b);
aa1.Fmethod("aa");
aa2 = aa1;
Console.ReadLine();
}
}
根据 docs:
Generic classes are invariant. In other words, if an input parameter specifies a
List<BaseClass>
, you will get a compile-time error if you try to provide aList<DerivedClass>
.
应用于您的示例,因为您将 a1<string>
类型的对象分配给 a1<object>
类型的变量,所以会出现错误。