问题描述
将派生类铸造为基类
我有一个通用的基本抽象类,它继承自IComparable,其定义如下
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();
}
}
由于泛型是字符串,并且字符串是从IComparable继承的,所以我希望能够将具有字符串值的新Name对象定义为泛型,但是这样定义Name对象时会出现强制转换错误:
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");
,错误是
推荐答案
您要声明类型为BaseClass<T>
的变量,并将T
替换为IComparable
.
You're declaring a variable of type BaseClass<T>
, and substitute T
with IComparable
.
那是有效的,但这不是您的Name
类的 .即使string
实现了IComparable
,该内容还是来自BaseClass<string>
,不是 BaseClass<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
.
您可以将变量obj
声明为BaseClass<string>
类型,或者将其派生为其他类型Name
.
You can either declare your variable obj
to be of type BaseClass<string>
, or the more derived type, Name
.
阅读协方差, C#泛型继承问题.
这篇关于面向对象的投放错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!