【问题标题】:How do I determine the instantiated name of a class when I create it创建类时如何确定类的实例化名称
【发布时间】:2011-10-08 19:32:01
【问题描述】:

我有一个包含一些成员和属性的类,当我创建它时,我如何知道创建时实例化的名称是什么?

我有一个 PDInt 类,所以我将它实例化为一个成员,然后将该成员包装在一个属性中。这是类,后面是属性:

    public class PDInt : PDBase
{
    #region Members

    int m_Value;
    public int Value
    {
        get
        {
            return m_Value;
        }
        set
        {
            if ( m_Value != value )
            {

            }
        }
    }

    #endregion

    public PDInt()
    {
        this.Init();
    }

    public PDInt( int Value )
    {
        this.Init();
        this.Value = Value;
    }

    public PDInt( int Value, string ControlName )
    {
        this.Init();

        this.Value       = Value;
        this.ControlName = ControlName;
    }

    private void Init()
    {
        this.Value = 0;
    }

    public void Map( int Value, string ControlName )
    {
        this.Value       = Value;
        this.ControlName = ControlName;
        this.Validate    = true;
    }

    public void Map( int Value, string ControlName, bool Validate )
    {
        this.Value       = Value;
        this.ControlName = ControlName;
        this.Validate    = Validate;
    }
}

这里是成员,然后是属性用法

        PDInt m_PrescriptionID;
    public PDInt PrescriptionID
    {
        get
        {
            if ( m_PrescriptionID == null )
            {
                m_PrescriptionID = new PDInt();
            }

            return m_PrescriptionID;
        }
        set
        {
            if ( m_PrescriptionID == null )
            {
                m_PrescriptionID = new PDInt();
            }
        }
    }

能够以编程方式确定实际实例化的名称对我非常有帮助,这样我就可以将它放在类内部的字符串中以供稍后引用。

我在整个应用程序中都使用反射,但在实例化类时我似乎无法弄清楚如何获取名称。

谢谢。

【问题讨论】:

  • 实例化名 == 变量名???

标签: c# reflection dynamic properties


【解决方案1】:

如果我理解正确,您想知道在类中实例化该类时从其他地方使用的实例名称是什么?

如果是这样 - 你不能。 c# 不允许这样做。

编辑:

你为什么需要它?也许你有一个可以通过其他方式解决的问题?

【讨论】:

  • 感谢您的提问。我想知道类在实例化时的名称,以便我可以使用它来填充类中的 Name 属性。这样,如果我以后需要知道类的名称,我就不必使用反射。
  • 这不是类的名称,它是实例的名称。你必须手动设置它。例如,在构造函数中 this.Foo = new Bar("Foo");
  • 是的,我想知道类的实例是什么,在创建过程中以编程方式进行。
猜你喜欢
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多