0

オブジェクトを渡し、そのオブジェクトへの参照を保持しているオブジェクトを取り戻す方法はありますか?

例:

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フォームソリューションでデータバインディングを単純化するために使用します。

これが私がそれを使うところです:

    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);

だから...これが起こる可能性はありますか?または、私が気付いていない、より簡単なバインド方法がありますか?

4

2 に答える 2

2

オブジェクトを渡し、そのオブジェクトへの参照を保持しているオブジェクトを取り戻す方法はありますか?

いいえ、一般的に。デバッガーAPIを使用している場合、これを行う方法はいくつかありますが、デバッグ目的のみです。あなたのプロダクションデザインはそれを必要とすべきではありません。

ただし、代わりに式ツリーを使用できる可能性があります。

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

...そして、式ツリーから、元のオブジェクトとそれが使用しているプロパティの両方を計算します。

于 2012-11-27T14:06:37.070 に答える
0

オブジェクトを渡し、そのオブジェクトへの参照を保持しているオブジェクトを取り戻す方法はありますか?

いいえ、組み込み機能としては使用できません。コードでそれを設計する必要があります。オブジェクト自体は、それを指す参照についての知識を持っていません。これは、これGCを追跡する義務です。

于 2012-11-27T14:06:17.767 に答える