簡體   English   中英

C#引用屬性的類的名稱

[英]C# Name of class that references a property

無論如何傳遞一個對象並獲取包含它的引用的對象?

例:

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窗體解決方案中簡化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);

那么......發生這種情況的機會是什么? 或者有一種我不知道的更簡單的綁定方式?

無論如何傳遞一個對象並獲取包含它的引用的對象?

不,一般而言。 如果您正在使用調試器API, 可能有一些方法可以執行此操作,但用於調試目的。 您的生產設計不應該要求它。

您可以使用表達式樹來代替:

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

...從表達式樹中找出原始對象和它正在使用的屬性。

無論如何傳遞一個對象並獲取包含它的引用的對象?

不,它不可能作為內置功能。 您必須在代碼中構建它。 對象本身並不了解指向它的引用。 這是一項GC職責,需要對此進行跟蹤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM