代码之家  ›  专栏  ›  技术社区  ›  Thomas Flinkow

结构默认构造函数上的属性

  •  3
  • Thomas Flinkow  · 技术社区  · 7 年前

    as结构不能有显式的用户定义的无参数构造函数,例如

    public struct MyStruct
    {
        public MyStruct() { … } // Not allowed!
    }
    

    我想知道是否以及如何将一个属性应用于那个精确的构造函数。 最后,我要做的是(最好是无参数构造函数可以是私有的,但这也是不允许的):

    public struct MyStruct
    {
        [Obsolete("Do not call the constructor directly, use MyStruct.Get() instead.")]
        public MyStruct() { … }
    
        public static MyStruct Get
        {
          // Important initializing here.
        }
    }
    

    有像这个虚构的属性目标这样的东西吗 [constructor: Obsolete()] 哪个允许将属性应用于默认构造函数?

    编辑:更多信息。

    情况是这样的:我需要使用 MyStruct 对于P/Invoke,不能使用类。我想警告用户,他们不应该获得 密苏里 因为它错过了重要的初始化,所以它们应该改用工厂方法。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Hossein Golshani    7 年前

    因为结构本身就是一个值类型 你找不到任何方法 .

    即使您是否实例化了一个结构,它也将被实例化。

    int x = new int(); 等于 int x;

    MyStruct s = new MyStruct(); 等于 MyStruct s;

    假设你能找到一种方法来警告 mystruct s=new mystruct(); . 任何定义 密苏里; 也会受到警告!那就没有办法了。