Мне нужно знать, есть ли лучший способ написать этот код. В SomeMethod()
ниже я sh верну тип IMyInterface
, но возвращаемый объект может быть создан как Class1
или Class2
на основе условия. Class2
имеет дополнительное свойство, которое имеет смысл, только если условие ложно.
public interface IMyInterface
{
int Prop1 { get; set; }
string Prop2{ get; set; }
}
public class Class1: IMyInterface
{
public int Prop1 { get; set; }
public string Prop2{ get; set; }
}
public class Class2: IMyInterface
{
public int Prop1 { get; set; }
public string Prop2{ get; set; }
public string AdditionalProp{ get; set; }
}
public class SomeClass
{
public IMyInterface SomeMethod(bool cond)
{
IMyInterface foo;
if (cond)
{
foo = new Class1();
}
else
{
foo = new Class2();
}
foo.Prop1 = 1;
foo.Prop1 = "1";
if (!cond)
{
foo.AdditionalProp = "2";
}
}
}