【发布时间】:2012-04-20 16:35:51
【问题描述】:
重新表述了这个问题。向下滚动查看原文
好吧,也许我应该给你完整的图片。我有很多类看起来像这样:
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 中,我需要从除了parameter 之外什么都没有得到fooInstance。从上下文来看,可以假设没有任何整数被传递到 DoSomething,而只是 ints 的公共属性。
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 上的自定义属性?
【问题讨论】:
-
你必须重新考虑你的设计。这是不可能的。
-
我不明白你的要求......你为什么不能把
Foo作为参数? -
为什么不能作为其他参数传入?
-
感谢大家的回答。也许我应该更改问题的标题,因为我的问题主要与通用属性更改通知的实现有关,svick 已经回答了这个问题
标签: c# reflection