有人能解释或指向解释为什么运行时类型检查不低于样品发生 - 字符串属性可以设置为任何类型的值...
非常意想不到的地方有这样闷和真的很惊讶DynamicMethod的和类型检查
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace Dynamics
{
internal class Program
{
private static void Main(string[] args)
{
var a = new A();
a.Name = "Name";
Console.WriteLine(a.Name.GetType().Name);
PropertyInfo pi = a.GetType().GetProperty("Name");
DynamicMethod method = new DynamicMethod(
"DynamicSetValue", // NAME
null, // return type
new Type[]
{
typeof(object), // 0, objSource
typeof(object), // 1, value
}, // parameter types
typeof(Program), // owner
true); // skip visibility
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, pi.GetSetMethod(true));
gen.Emit(OpCodes.Ret);
SetValue setMethod = (SetValue)method.CreateDelegate(typeof(SetValue));
int val = 123;
setMethod(a, val);
Console.WriteLine(a.Name.GetType().Name);
A anotherA = new A();
anotherA.Name = "Another A";
setMethod(a, anotherA);
Console.WriteLine(a.Name.GetType().Name);
}
}
public class A
{
public string Name { get; set; }
}
public delegate void SetValue(object obj, object val);
}
其实我预计分配给A.Name一定的价值,而不是通过方法参数打字时类型检查。 pi.SetValue(a,123)将导致带有关于对象类型转换错误的文本的ArgumentException,但SetValue方法也接受对象作为参数。 –
实际上发生参考更改没有类型检查... –