1.dynamic
对C#编译器,通过dynamic声明的数据点可以分配任何初始值。
而且可以在其生命周期内重新分配任何新的值。
static void ChangeDynamicDataType()
{
dynamic t = "hello";
t = false;
t = new List<int>();
}
动态数据不属于静态类型,直到运行时才知道数据的类型。
static void InvokeMembersOnDynamicData()
{
dynamic textData1 = "Hello";
try
{
textData1.toupper();
}
catch(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine(ex.Message);
}
}
2.dynamic可以用于 本地变量,返回值,参数,类/结构成员。
3.限制:
调用动态类型的方法时,传递参数不能用Lambda,匿名方法。
static void CreateUsingLateBinding(Assembly asm)
{
try
{
Type miniVan = asm.GetType("CarLibrary.MiniVan");
object obj = Activator.CreateInstance(miniVan);
MethodInfo mi = miniVan.GetMethod("TurboBoost");
mi.Invoke(obj, null);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// 动态类型,让过程变得简单
static void InvokeMethodWithDynamicKeyword(Assembly asm)
{
try
{
Type miniVan = asm.GetType("CarLibrary.MiniVan");
dynamic obj = Activator.CreateInstance(miniVan);
obj.TurboBoost();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void AddWithReflection()
{
Assembly asm = Assembly.Load("MathLibrary");
try
{
Type math = asm.GetType("MathLibrary.SimpleMath");
object obj = Activator.CreateInstance(math);
MethodInfo mi = math.GetMethod("Add");
object[] args = {10, 70};
Console.WriteLine("Result is:{0}", mi.Invoke(obj, args));
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void AddWithDynamic()
{
Assembly asm = Assembly.Load("MathLibrary");
try
{
Type math = asm.GetType("MathLibrary.SimpleMath");
dynamic obj = Activator.CreateInstance(math);
Console.WriteLine("Result is:{0}", obj.Add(10, 70));
}
catch(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine(ex.Message);
}
}