我想知道是否有更好的方法来写这段代码。在下面的SomeMethod()中,我希望返回IMyInterface类型,但根据条件,返回的对象可以创建为Class1或Class2。Class2有一个额外的属性,只有在条件为false时才有意义。
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";
}
}
}发布于 2020-03-27 01:21:38
听起来像factory pattern。您的代码和链接示例中的代码之间的唯一区别是,在您的示例中,工厂的get方法的参数是bool,而不是type。下面是它看起来的样子:
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; }
}
/// <summary>
/// Implementation of Factory - Used to create objects
/// </summary>
public class Factory
{
public IMyInterface GetClass(bool condition)
{
if (condition)
{
return new Class1();
}
else
{
return new Class2();
}
}
}发布于 2020-03-27 01:18:07
如果我没弄错你的要求,下面的方法就解决了你的问题。
您可以内联初始化对象:
public IMyInterface SomeMethod(bool cond)
{
IMyInterface foo;
if (cond)
{
foo = new Class1();
}
else
{
foo = new Class2() { AdditionalProp = "2" };
}
foo.Prop1 = 1;
foo.Prop2 = "1";
return foo;
}发布于 2020-03-27 01:23:17
这里有一个优雅的解决方案:
public IMyInterface SomeMethod(bool cond)
{
return cond
? (IMyInterface) new Class1 { Prop1 = 1, Prop2 = "1" }
: new Class2 { Prop1 = 1, Prop2 = "1", AdditionalProp = "2" };
}https://stackoverflow.com/questions/60872527
复制相似问题