質問を言い換えました。原文は下にスクロール
わかりました、多分私はあなたに全体像を与えるべきでした. 私は次のような多くのクラスを持っています:
public class Movement : Component
{
private Vector3 linearVelocity;
public Vector3 LinearVelocity
{
get
{
return linearVelocity;
}
set
{
if (value != linearVelocity)
{
linearVelocity = value;
ComponentChangedEvent<Movement>.Invoke(this, "LinearVelocity");
}
}
}
// other properties (e.g. AngularVelocity), which are declared exactly
// the same way as above
}
Transform、Mesh、Collider、Appearance などと呼ばれるクラスもあります。これらはすべてから派生しComponent
、上記のように宣言されたプロパティのみを持ちます。ここで重要なのは、ComponentChangedEvent
. すべてが完璧に機能しますが、プロパティごとに同じロジックを何度も書き直す必要がない方法を探していました。
hereを見て、ジェネリックプロパティを使用するというアイデアが気に入りました。私が思いついたのは次のようになります。
public class ComponentProperty<TValue, TOwner>
{
private TValue _value;
public TValue Value
{
get
{
return _value;
}
set
{
if (!EqualityComparer<TValue>.Default.Equals(_value, value))
{
_value = value;
ComponentChangedEvent<TOwner>.Invoke(
/*get instance of the class which declares value (e.g. Movement instance)*/,
/*get name of property where value comes from (e.g. "LinearVelocity") */);
}
}
}
public static implicit operator TValue(ComponentProperty<TValue, TOwner> value)
{
return value.Value;
}
public static implicit operator ComponentProperty<TValue, TOwner>(TValue value)
{
return new ComponentProperty<TValue, TOwner> { Value = value };
}
}
次に、次のように使用します。
public class Movement : Component
{
public ComponentProperty<Vector3, Movement> LinearVelocity { get; set; }
public ComponentProperty<Vector3, Movement> AngularVelocity { get; set; }
}
しかし、LinearVelocity が由来するインスタンスも文字列としての名前も取得できません。だから私の質問は、これがすべて可能かどうかでした...
しかし、各プロパティのこのロジックを手動で記述して、これまでどおりに実行する以外に選択肢はないようです。
元の質問:
プロパティから宣言クラスのインスタンスを取得する
プロパティを持つクラスがあります:
public class Foo
{
public int Bar { get; set; }
}
別のコンテキストでは、次のようなものがあります。
Foo fooInstance = new Foo();
DoSomething(fooInstance.Bar);
次に、DoSomething
私はfooInstance
何も持たないことから取得する必要がありparameter
ます。DoSomething
コンテキストから、整数は に渡されず、int のパブリック プロパティのみが渡されると仮定しても問題ありません。
public void DoSomething(int parameter)
{
// need to use fooInstance here as well,
// and no, it is not possible to just pass it in as another parameter
}
それはまったく可能ですか?リフレクション、またはプロパティのカスタム属性を使用していますBar
か?