问题
Casting Deriving Class as Base Class
I have a base abstract class which is generic and inherits from IComparable which is defined like below
public abstract class BaseClass<T> where T : IComparable
{
protected readonly T Data;
protected BaseClass(T data)
{
Data = data;
}
public abstract T Get();
}
Then I have defined a classe which inherits from this base class and has a specific generic type and is defined like below:
public class Name : BaseClass<String>
{
public Name(string data) : base(data)
{
}
public override string Get()
{
throw new NotImplementedException();
}
}
As generic type is string and string inherits from IComparable, I expect to be able to define new Name object with string value as generic type, but I get casting error for defining Name object like this:
BaseClass<IComparable> obj;
obj = new Name("behro0z");
and the error is
Error CS0029 Cannot implicitly convert type
ConsoleApplication1.NametoConsoleApplication1.BaseClass<System.IComparable>ConsoleApplication1
回答1:
You're declaring a variable of type BaseClass<T>, and substitute T with IComparable.
That's valid, but that's not what your Name class is. That one derives from BaseClass<string>, not BaseClass<IComparable>, even though string implements IComparable.
You can either declare your variable obj to be of type BaseClass<string>, or the more derived type, Name.
Read up on covariance, C# Generics Inheritance Problem.
来源:https://stackoverflow.com/questions/51132087/object-oriented-casting-error