【问题标题】:Is "this" static? Checking for Static in the constructor“这个”是静态的吗?在构造函数中检查静态
【发布时间】:2022-06-16 00:51:18
【问题描述】:

我需要在构造函数中确定类 T 的成员 T 是否是静态成员。我预计这将涉及检查“this”的某些属性,但我无法确定要查找的内容。

public class Thing
{
    public static readonly Thing StaticThing = new ("StaticThing");
    public Thing NonStaticThing = new("NonStaticThing");
    public string Name { get; set; }
    private Thing(string name) 
    {
        Name = name;
        if(this.IsStatic)  //how to determine if the thing being constructed is static?
        { /* Do something special with a static thing */ }
    }

}

我如何识别Static 属性是否应用于this

【问题讨论】:

  • “如果正在构造的东西是静态的” - 不可能。上下文(作为静态字段)不会传递给构造函数。
  • 如果它正在被构造,它总是是一个实例。除非您正在考虑 static constructor - 在这种情况下,它总是静态)
  • 这里的一个常见模式是拥有一个带有特殊签名的私有构造函数,您可以为自己的预制实例调用该构造函数。

标签: c# .net system.reflection


猜你喜欢
  • 1970-01-01
  • 2011-02-24
  • 2021-11-08
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 2013-12-25
相关资源
最近更新 更多