假设我们有一个包含一些组件(对象字段)的类,其中一些组件可以为null(已删除) 是否适合在没有(组件)字段的情况下创建新类或使用接口来处理它。假设我们有几个组件可以为某些对象删除 Thx提前
public class Class1{
Component1 component1;
Component2 component2;
Component3 component3;//can be null (removed)
Component4 component4;//can be null (removed)
}
public class Class2{//removed component3,component4(new class)
Component1 component1;
Component2 component2;
}
public class Class3{//removed component3(new class)
Component1 component1;
Component2 component2;
Component4 component4;
}
public class Class4{//removed component4(new class)
Component1 component1;
Component2 component2;
Component3 component3;
}
或使用界面
public interface IComponent1{
}
public class Component1:IComponent1{
}
public class NoComponent1:IComponent1{
}
public interface IComponent2{
}
public class Component2:IComponent2{
}
public class NoComponent2:IComponent2{
}
public interface IComponent3{
}
public class Component3:IComponent3{
}
public class NoComponent3:IComponent3{
}
public interface IComponent4{
}
public class Component4:IComponent4{
}
public class NoComponent4:IComponent4{
}
public class Class1{
IComponent1 componentBehaviour1;
IComponent2 componentBehaviour2;
IComponent3 componentBehaviour3;
IComponent4 componentBehaviour4;
}
或在类的方法中检查null条件(如果需要)。
答案 0 :(得分:0)
根据我的经验,最好遵循面向对象的原则。在你的情况下,我认为你应该首先为所有必填字段创建一个类:
public class Class1{
Component1 component1;
Component2 component2;
}
然后为每个可空字段使用接口,例如:
public Interface interface1{
Component1 component3;
}
然后是另一个界面:
public Interface interface2{
Component1 component4;
}
然后在课堂上你可以:
public class Class2: Class1, interface1
还有另外一个类:
public class Class2: Class1, interface2
public class Class3: Class1, interface1, interface2
答案 1 :(得分:0)
public interface IComponent{}
public class Foo{
private readonly IList<IComponent> _components;
public void AddComponent(IComponent component){
// do your magic here
}
public IEnumerable<T> GetComponents<T>() where T : IComponent {
// do your magic here
}
}