[英]C# - Having an object from multiple classes
I have three different classes in my current project structured as below: 我目前的项目中有三个不同的类,结构如下:
class BaseClass {
public string prop1;
public string prop2;
public string prop3;
}
class C1 : BaseClass {
public string prop3; // Common with class C2
public string prop4;
}
class C2 : BaseClass {
public string prop3; // Common with class C1
public string prop5;
}
I need to have an object which includes prop1, prop2, prop3, prop4, and prop5; 我需要一个包含prop1,prop2,prop3,prop4和prop5的对象; but I don't want to have a duplication definition.
但我不想有重复定义。 I don't want to create a new class like this:
我不希望创建这样一个新的类:
class NewClass {
public string prop1;
public string prop2;
public string prop3;
public string prop4;
public string prop5;
}
Is there a way (like interface, or abstract class, or anything else) that I can refactor my old classes into so that I can have an object with all 5 properties without defining a new class? 有没有一种方法(比如接口,抽象类或其他任何东西)我可以重构我的旧类,以便我可以拥有一个包含所有5个属性的对象而无需定义新类?
Definitely interfaces, just be aware that for matter of theory correctness, you would be implementing methods, not properties, a property is something different in C#. 绝对是接口,只要注意理论上的正确性,你将实现方法,而不是属性,属性在C#中是不同的。 (Link: Properties in C# )
(链接: C#中的属性 )
public interface IBaseClass
{
public string GetProperty1();
public string GetProperty2();
public string GetProperty3();
}
public interface IC1
{
public string GetProperty4();
}
public interface IC2
{
public string GetProperty5();
}
public class Implementation : IBaseClass, IC1, IC2
{
public string GetProperty1()
{
return "Value";
}
public string GetProperty2()
{
return "Value";
}
public string GetProperty3()
{
return "Value";
}
public string GetProperty4()
{
return "Value";
}
public string GetProperty5()
{
return "Value";
}
}
The benefit of doing it like this, is that the implementation class is forced to define such methods. 这样做的好处是实现类被迫定义这样的方法。
Will this help? 这会有帮助吗?
class BaseClass
{
public virtual string prop1 { get; set; }
public virtual string prop2 { get; set; }
public virtual string prop3 { get; set; }
public virtual string prop4 { get; set; }
public virtual string prop5 { get; set; }
}
class C1 : BaseClass
{
public override string prop4 { get; set; }
}
class C2 : BaseClass
{
public override string prop5 { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.