改写了这个问题。向下滚动以获取原始图片属性更改通知属性
好的,也许我应该给你整张照片。我有很多类,看起来是这样的:
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
}
还有一些类称为变换,网格,对撞机,外观等都是从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
,而只是整数的公有属性。
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
上的自定义属性?
你将不得不重新考虑你的设计。这不可能。 – BrokenGlass 2012-04-20 16:38:35
我不明白你在问什么......为什么你不能给'Foo'作为参数? – log0 2012-04-20 16:40:30
为什么你不能将它作为另一个参数传入? – 2012-04-20 16:43:23