【发布时间】:2020-04-21 22:49:01
【问题描述】:
我只是对这个例子有疑问。 在我的类中使用静态函数来创建具有正确类型的对象。 这是一个编码标准还是很奇怪?
public partial class Example
{
public enum enumType
{
typeA,
typeB
}
private string type;
public Example(enumType type)
{
if ( type == enumType.typeA)
{
this.type = enumType.typeA.ToString();
}
else
{
this.type = enumType.typeB.ToString();
}
}
public static Example CreateAsTypeA()
{
return new Example(enumType.typeA);
}
public static Example CreateAsTypeB()
{
return new Example(enumType.typeB);
}
}
【问题讨论】:
-
我不确定,但我认为这是代码异味。比如直接调用构造函数,为什么还要创建静态方法?
-
这个示例已经违反了几个“标准”,虽然
static方法似乎用处不大,但它们确实为用户减少了 4 次击键的“好处”。 (即var e = Example.CreateAsTypeA();而不是var e = new Example(enumType.typeA); -
我也许可以给你更多的信息。我的公司在每种情况下都设置了更多的财产。构造函数仍然需要公开,因为它是一个 WPF MVVM 项目并且需要调用构造函数。他们向我解释了不同枚举留在类中并且无法从外部访问并且类只能以 2 种方式(A 或 B)初始化的好处
-
类内部的枚举成员变量不能从外部访问,但枚举定义可以从外部访问。可以拨打
return new Example(Example.enumType.typeA)这样,一点好处都没有。
标签: c# wpf coding-style