public class User
{
//使用省缺参数,一般不需要再为多态做各种静态重载了
public User( string name = "anonym", string type = "user" )
{
this.UserName = name;
this.UserType = type;
}
public UserName { private set; get; }
public UserType { private set; get; }
}
User user = new User(); //不带任何参数实例化
Console.WriteLine( user.UserName ); //输出 anonym
Console.WriteLine( user.UserType ); //输出 user
// dynamic 关键字可以绕过静态语言的强类型检查
dynamic d = user;
Console.WriteLine( d.UserName ); //输出 anonym
Console.WriteLine( d.UserType ); //输出 user
// ExpandoObject 是一个特殊对象,包含运行时可动态添加或移除的成员
dynamic eo = new System.Dynamic.ExpandoObject();
eo.Description = "this is a dynamic property";
Console.WriteLine( eo.Description ); // 输出 this is a dynamic property
//继承 DynamicObject 类,重写 TryInvokeMember 虚拟方法
public class Animal : DynamicObject
{
//尝试执行成员,成功返回 true,并从第二个参数输出执行后的返回值
public override bool TryInvokeMember( InvokeMemberBinder binder,
object[] args, out object result)
{
bool success = base.TryInvokeMember( binder, args, out result);
//基类尝试执行方法,返回 false,表示方法不存在,out 输出 null 值
//if (! success) result = null;
//若返回 false 将抛出异常
return true;
}
}
//派生动态类
public class Duck : Animal
{
public string Quack()
{
return "Quack!!";
}
}
//派生动态类
public class Human : Animal
{
public string Talk()
{
return "Talk!!";
}
}
//调用动态方法
public static string DoQuack( dynamic animal )
{
string result = animal.Quack();
return result ?? "Null"; //(result == null)? "Human" : result;
}
var duck = new Duck();
var human = new Human();
Console.WriteLine( DoQuack( duck ) ); //输出 Quack
Console.WriteLine( DoQuack( human ) ); //输出 Null , Human类不包含Quack方法,执行失败
C# 4 dynamic 动态对象 动态类型转换