例如:
Class Person{
string Name;
int Age;
void Work(){
//此处Work方法仅在Age大于等于16岁时起效
//即,若属性Age小于16岁,此Person视为不存在Work方法
}
}
例如:
Class Person{
string Name;
int Age;
void Work(){
//此处Work方法仅在Age大于等于16岁时起效
//即,若属性Age小于16岁,此Person视为不存在Work方法
}
}
可以用委托实现:
Class Person{
string Name;
int Age;
public Person(string s, int a) { Name = s, Age = a; }
public Action Work
{
get { if (Age > 16) return () => { Console.WriteLine("work"); }; else return () => {}; }
}
}
调用
Person p = new Person("aa", 20);
p.Work();
Person p1 = new Person("bb", 12);
p1.Work();
顺便说下,attribute单纯使用不能适用这个场景,需要通过dynamic proxy封装。但是会改变你的调用者代码。
除了使用委托,还有就是用emit/codedom动态生成代码
你还可以不用lambda表达式
Class Person{
string Name;
int Age;
public Person(string s, int a) { Name = s, Age = a; }
public Action Work
{
get { if (Age > 16) return new Action(work); else throw new NotImplementedException(); }
}
private void work()
{
...
}
}
你提到类似System.ObsoleteAttribute,是否可以有自己的特性,这个不行,因为判断这些特性的逻辑写死在编译器里,没办法扩展。