2012-11-27 66 views
0

是否有反正傳遞一個對象並找回包含引用的對象?C#引用屬性的類的名稱

實施例:

public class Person 
{ 
    public string Name { get; set; } 

    public Person(string name) 
    { 
     this.Name = name; 
    } 
} 

public static class Helper 
{ 

    public static void IsItPossible() 
    { 
     var person = new Person("John Doe"); 

     var whoKnowsMe = WhoIsReferencingMe(person.Name); 

     //It should return a reference to person 
    } 

    public static object WhoIsReferencingMe(object aProperty) 
    { 
     //The magic of reflection 
     return null; 
    } 
} 

這裏的代碼是啞。但我將用於簡化Windows Form解決方案中的DataBinding。

這裏就是我會使用它:

protected void Bind(object sourceObject, object sourceMember, 
     Control destinationObject, object destinationMember) 
    { 
     //public Binding(string propertyName, object dataSource, string dataMember); 
     string propertyName = GetPropertyName(() => destinationMember); 
     string dataMember = GetPropertyName(() => sourceMember); 

     Binding binding = new Binding(propertyName, sourceObject, dataMember); 

     destinationObject.DataBindings.Add(binding); 
    } 

    public string GetPropertyName<T>(Expression<Func<T>> exp) 
    { 
     return (((MemberExpression)(exp.Body)).Member).Name; 
    } 

的原因是,該功能是一種多餘的:

this.Bind(viewModel.Client, viewModel.Client.Id, view.icClientId, tiew.icClientId.Text); 

我問,以便將其簡化爲這樣:

this.Bind(viewModel.Client.Id, view.icClientId.Text); 

那麼......發生這種情況的可能性有多大?或者有一種我不知道的更簡單的綁定方式?

回答

0

反正有沒有辦法傳遞一個對象並取回包含 引用的對象?

不,它不可能作爲內置功能。你必須在你的代碼中構建它。 對象本身並不知道指向它的引用。這是一個GC的職責,來跟蹤這一點。

2

反正有沒有辦法傳遞一個對象並找回引用它的對象?

不,一般來說。有可能是如果您使用調試器API,但爲了調試目的而使用只有的方法。你的生產設計不應該要求它。

你可能使用表達式目錄樹來代替,但:

this.Bind(() => viewModel.Client.Id,() => view.icClientId.Text); 

...從表達式樹都發起對象和它的使用屬性鍛鍊。

+0

呃......如果Jon Skeet說表情樹是唯一的出路,我可能會保持原樣。我已經在反思中掙扎了。甚至無法想象試圖圍繞表情樹包裹我的頭。 –