例如:
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,是否可以有自己的特性,这个不行,因为判断这些特性的逻辑写死在编译器里,没办法扩展。
Work方法中,如果Age<16就Return 就OK
至于你方的效果不存在的
没有这种代码,不允许类里既有一个函数又没有。
除非你实现两个类,一个成年人(大于16岁),一个未成年人,然后构造的时候根据年龄判断构造哪个类。
class Person{
Person(int a);
int age;
}
class Adolescent: Person{
Adolescent(int a);
}
class Adult: Person{
Adult(int a);
void work();
}
Person createPerson(int age){
if( age <= 16 )
return Adolescent(age);
else
return Adult(age);
}
如果只是希望小于16岁函数不工作,这么写
class Person{
int age;
void work(){
if( age <= 16 )
return;
//你的代码
}
}