【发布时间】:2015-08-01 15:47:48
【问题描述】:
我开始潜入C# Dynamics and Metaprogramming 的世界,遇到了一些麻烦。
我设法创建了一个CodeDom 树,并生成了以下代码:
namespace Mimsy {
using System;
using System.Text;
using System.Collections;
internal class JubJub {
private int _wabeCount;
private ArrayList _updates;
public JubJub(int wabeCount) {
this._updates = new ArrayList();
this.WabeCount = wabeCount;
}
public int WabeCount {
get {
return this._wabeCount;
}
set {
if((value < 0))
this._wabeCount = 0;
else
this._wabeCount = value;
this._updates.Add(this._wabeCount);
}
}
public string GetWabeCountHistory() {
StringBuilder result = new StringBuilder();
int ndx;
for(ndx = 0; (ndx < this._updates.Count); ndx = ndx + 1) {
if((ndx == 0))
result.AppendFormat("{0}", this._updates[ndx]);
else
result.AppendFormat(", {0}", this._updates[ndx]);
}
}
}
}
然后,我将此命名空间动态编译为名为 "dummy" 的程序集。
我可以成功得到这个类型的一个实例:
string typeName = "Mimsy.JubJub";
Type type = dummyAssembly.GetType(typeName);
dynamic obj = Activator.CreateInstance(type, new object[] { 8 });
//obj is a valid instance type
如果我调试这段代码,我可以在调试器中看到obj 实际上具有属性WabeCount:
但是,当试图访问这个属性时,编译器会喊出动态属性不存在。
【问题讨论】:
-
wabes[ndx]的类型是什么?他们是int吗? -
它们实际上是
int包装为object的值 -
尝试将它们投射到
(int),例如obj.WabeCount = (int)wabes[ndx] -
@xanatos 我尝试投射它们,但问题仍然存在
-
不要在课堂上使用
internal!dynamic可能不喜欢!使用public。然后进行选角...(所以试试public class和obj.WabeCount = (int)wabes[ndx])(见stackoverflow.com/a/18806787/613130)
标签: c# .net dynamic reflection metaprogramming