110,499
社区成员
发帖
与我相关
我的任务
分享
var des = T.GetProperty(PerportyName);
怎么查询都是空值,请高手指点。
class Program
{
static void Main(string[] args)
{
List<string> myList = new List<string>();
myList.Add("Name");
myList.Add("Age");
myList.Add("Hobby");
//先创建动态属性
dynamic dynamicModel = new DynamicModel();
for (int i = 0; i < myList.Count; i++)
{
dynamicModel.PropertyName = myList[i] + "_A";
dynamicModel.PropertyName = myList[i] + "_B";
}
//后根据前置属性赋值
Type T = typeof(DynamicModel);
string PerportyName = "Name_A";
var des = T.GetProperty(PerportyName);//****这里,为啥一直查询不到"Name_A"呢****
des.SetValue(dynamicModel, "fdfdfdf", null);
}
}
public class DynamicModel : DynamicObject
{
private string propertyName;
public string PropertyName
{
get { return propertyName; }
set { propertyName = value; }
}
// The inner dictionary.
Dictionary<string, object> dicProperty
= new Dictionary<string, object>();
public Dictionary<string, object> DicProperty
{
get
{
return dicProperty;
}
}
// This property returns the number of elements
// in the inner dictionary.
public int Count
{
get
{
return dicProperty.Count;
}
}
// If you try to get a value of a property
// not defined in the class, this method is called.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
string name = binder.Name;
// If the property name is found in a dictionary,
// set the result parameter to the property value and return true.
// Otherwise, return false.
return dicProperty.TryGetValue(name, out result);
}
// If you try to set a value of a property that is
// not defined in the class, this method is called.
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
if (binder.Name == "Property")
{
dicProperty[PropertyName] = value;
}
else
{
dicProperty[binder.Name] = value;
}
// You can always add a value to a dictionary,
// so this method always returns true.
return true;
}
}