【发布时间】:2013-09-15 01:08:13
【问题描述】:
我需要能够存储对对象属性的引用,以便以后读取/写入,最好不使用反射。我也对一种也可以使用的设计模式持开放态度,但性能至关重要,因为我的应用程序将在各种“父”类上进行数百万次“运行”调用。下面的代码模板应该解释我想要做什么。
我想保留它,以便我“需要”的变量是 Child 类的对象属性,而不是存储在某个列表中的数据结构,例如。
最后,我想我正在寻找的不仅仅是重置对象值或检查非空值。例如,在调用 _run 之后,Parent 可能会将属性的值用于其他用途。
谢谢。
class requiredAttribute : Attribute
{
}
abstract class Parent
{
abstract protected void _run();
public Parent() {
// This can do whatever set-up is necessary in order to make the below run() call
// not need reflection.
/* What code goes here? */
}
public void run() {
// This code should reset all 'required' properties to null.
/* What goes here? */
_run();
// This code needs to ensure any required property is now not null.
// If it finds a null one, it should throw.
/* What goes here? */
}
}
class Child : Parent
{
[required]
protected object value1;
[required]
protected object value2;
// not required..
protected object value3;
protected void _run() {
// This must set all 'required' properties' values, otherwise the Parent should throw.
value1 = "some value";
value2 = "some other value";
}
}
【问题讨论】:
-
什么版本的 .NET 框架?
-
4.5 - 这是满足字符配额的额外文本。
标签: c# properties