C# 具有一个属性的相同类类型不同
在我的项目中,我实现了两个相同的类,其中只有一个区别是其中一个属性的类型,我可以做些什么来避免这种代码冗余 将两个类中的所有公共代码移动到C# 具有一个属性的相同类类型不同,c#,.net,C#,.net,在我的项目中,我实现了两个相同的类,其中只有一个区别是其中一个属性的类型,我可以做些什么来避免这种代码冗余 将两个类中的所有公共代码移动到公共抽象类中。创建两个类,如下所示: public class ClassWithBool: MyAbstractClass { public bool Property{ get; set;} } public class ClassWithInt: MyAbstractClass { public int Property{ get; se
公共抽象类中
。创建两个类,如下所示:
public class ClassWithBool: MyAbstractClass
{
public bool Property{ get; set;}
}
public class ClassWithInt: MyAbstractClass
{
public int Property{ get; set;}
}
或者,将其设置为泛型类:
Public class MyClass<T>
{
// all code except your property
public T Property{get;set;}
}
公共类MyClass
{
//除您的属性外的所有代码
公共T属性{get;set;}
}
是否总是正好两个?或者理论上它应该适用于任何类型?对于后者:泛型,即类Foo{public int where{get;set;}public T TheOtherThing{get;set;}
;但如果正好有两种用法,则可能不合适-然后使用Foo
和Foo
(或任何用法)通过在一个类中保留相同的方法继承类,并且子类具有额外的属性代码是什么?您真的确定它们代表了足够相似的概念,以便将它们耦合在一起吗?