开发者

C# Get object name by instance

I have:

class A
{
 public object obj1 {get;set;}      
 public object obj2 {get;set;}      
 public object obj3 {get;set;}      
}

Somewhere i have instance of obj2 for example. How can i get its name ("obj2") without using cl开发者_开发问答ass A or instance A?


You can't do this. obj2 is the name of a property of the class A. So without using class A you cannot know its property names.


The only way is tracking the build process of class A, example:

public class Container
{
    Dictionary<string, object> _objectContainer;

    public Container()
    {
        _objectContainer = new Dictionary<string, object>();
    }

    public void SetByName( string name, object obj )
    {
        if( !_objectContainer.ContainsKey( name ) )
        {
            _objectContainer.Add( name, obj );
        }
        else
        {
            _objectContainer[name] = obj;
        }
    }

    public object GetByName( string name )
    {
        return _objectContainer[name];
    }
}

public class ABuilder
{
    public static A Build( Container container )
    {
        var a = new A();

        var obj1 = new object();
        var obj2 = new object();
        var obj3 = new object();

        container.SetByName( "obj1", obj1 );
        container.SetByName( "obj2", obj2 );
        container.SetByName( "obj3", obj3 );

        a.Obj1 = obj1;
        a.Obj2 = obj2;
        a.Obj3 = obj3;

        return a;
    }
}

class Program
{
    static void Main( string[] args )
    {
        var container = new Container();

        var obj = ABuilder.Build( container );

        var obj1 = container.GetByName( "obj1" );
    } 
}


To do this without the instance of class A, you have to modify the type of your properties :

class A
{
  private B obj1, obj2;

  public B Obj1 
  { 
    get { return obj1; }
    set 
    {
      if (value != null && value.Owner != null)
        throw new ArgumentException();
      if (obj1 != null)
        obj1.Owner = null;
      obj1 = value;
      obj1.Owner = "Obj1";
    }
  }
  public B Obj2
  {
    get { return obj2; }
    set
    {
      if (value != null && value.Owner != null)
        throw new ArgumentException();
      if (obj2 != null)
        obj2.Owner = null;
      obj2 = value;
      obj2.Owner = "Obj2";
    }
  }
}

class B
{
  public string Owner { get; internal set; }
  // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜