[b]新建类Product:
[/b]
class Product
{
public string name;
public int Id { get; set; }
public void ShowProduct()
{
Console.WriteLine("Id={0} ,Name={1}", Id, name);
}
}
[b]Main方法代码如下:
[/b]
static void Main(string[] args)
{
//dynamic对象
dynamic dynProduct = new Product();
//设置name字段
dynProduct.name = "n1";
//设置Id属性
dynProduct.Id = 1;
dynProduct.Id = dynProduct.Id + 3;
//调用ShowProduct方法
dynProduct.ShowProduct();
Console.ReadLine();
}
[b]输出如下:[/b]
[img]http://files.jb51.net/file_images/article/201305/2013051409211720.jpg[/img]
修改dynProduct.Id=”1”,此时"1”是字符串
[b]运行:[/b]
[img]http://files.jb51.net/file_images/article/201305/2013051409211721.png[/img]
因为product的Id属性是int型
修改dynProduct.ShowProduc[b]T[/b](); 运行:
[img]http://files.jb51.net/file_images/article/201305/2013051409211722.png[/img]
因为product 包含ShowProduct 的方法,但是并没有包含ShowProducT的方法,
所以dynamic不支持大小写不同。根本原因是因为C#也不支持。
修改Product中name的修饰符:将Public改为private:
private string name;
[b]再次运行代码:[/b]
[img]http://files.jb51.net/file_images/article/201305/2013051409211723.png[/img]
因为name是private,外部无法访问。。。
但是反射好像是可以的啊?
那么尝试下反射吧:
Type productType = typeof(Product);
Product p = new Product();
FieldInfo fi = productType.GetField("name",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
fi.SetValue(p, "通过反射设置的值");
[b]运行,结果如下:[/b]
[img]http://files.jb51.net/file_images/article/201305/2013051409211724.png[/img]
因为在某些安全限制条件下,是不运行读取和设置私有字段的,例如在silverlight中。所以微软大概出于对这一点的考虑,所以dynamic不支持私有字段的读取和设置吧,以上纯属个人猜想。