【问题标题】:Use static function into the class to return it initialize [closed]在类中使用静态函数将其返回初始化[关闭]
【发布时间】: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


【解决方案1】:

是的,你的方法应该是静态的。

因为它们本质上是在构造类的变体,所以不需要存储有关对象实例的任何内容。您的方法或多或少是构造函数,而不是太多属性。也就是说,您可能想研究静态构造函数的概念。这是一个链接:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多