object oriented Casting error [duplicate]

2019-07-15 07:11发布

This question already has an answer here:

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.Name to ConsoleApplication1.BaseClass<System.IComparable> ConsoleApplication1

1条回答
疯言疯语
2楼-- · 2019-07-15 07:30

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.

查看更多
登录 后发表回答