我有使用BaseClass的遗留代码,代码期望customerid是int类型。然后我需要创建一个新类DerivedClass,它的行为与BaseClass非常相似,但现在customerid需要是一个字符串。无法修改遗留代码,因此不需要进行测试。
如何使用继承(或任何其他方式)获得我想要的效果?
下面的Linqpad测试代码说明了我需要做什么。显然它不会编译,因为DerivedClass中的customerid需要为int。我还需要一个名为customerid的字符串属性。它必须是该名称,因为其他代码将使用此类而不是BaseClass,并期望相同的命名属性为string类型。
public class BaseClass
{
public virtual int customerid {get; set;}
public void printname()
{
customerid = 1;
customerid.Dump();
}
}
public class DerivedClass : BaseClass
{
public override string customerid {get; set;}
public void PrintCustomerID()
{
customerid = "jshwedeX";
customerid.Dump();
}
}
void Main()
{
DerivedClass dc = new DerivedClass();
dc.printname();
}
答案 0 :(得分:27)
您可以使用new
修饰符,如下所示:
public class BaseClass
{
public virtual int customerid {get; set;}
public void printname()
{
customerid = 1;
customerid.Dump();
}
}
public class DerivedClass : BaseClass
{
public new string customerid {get; set;}
public void PrintCustomerID()
{
customerid = "jshwedeX";
customerid.Dump();
}
}
这将为您提供所需的结果,但它也会隐藏基类的属性。如果您将DerivedClass
的实例引用为BaseClass
变量,则只能在基类上引用该属性;不是派生类。
换句话说:
BaseClass instance = new DerivedClass();
string customerId = instance.customerid; // <- this won't compile
另一种方法是使用显式接口实现:
public interface IBase
{
int customerid { get; set; }
}
public interface IDerived
{
string customerid { get; set; }
}
public class Derived : IBase, IDerived
{
int IBase.customerid { get; set; }
string IDerived.customerid { get; set; }
}
当您的Derived
实例存储在IBase
类型的变量中时,customerid
将解析为int
版本,并且当它存储在IDerived
的变量中时键入string
,它将解析为var derived = new Derived();
IBase ibase = derived;
IDerived iderived = derived;
int id1 = ibase.customerid; // <- compiles just fine
string id2 = iderived.customerid; // <- compiles just fine
版本:
var instance = new Derived();
int id1 = ((IBase)instance).customerid;
string id2 = ((IDerived)instance).customerid;
你也可以使用cast:
var instance = new Derived();
var customerid = instance.customerid; // <- this won't compile
请记住,除非变量属于接口类型,否则显式接口实现会导致实现的成员不可见:
{{1}}