gpt4 book ai didi

c# - 动态绑定(bind)对象属性和字符串

转载 作者:太空狗 更新时间:2023-10-29 23:22:39 24 4
gpt4 key购买 nike

我有一个下面的类

public class SearchModel
{
public string Locations { get; set; }
public string City { get; set; }
public string Address { get; set; }
public string MaxRecord { get; set; }
public string PageSize { get; set; }
....
....
Approx 80 properties
}

我有一个查询字符串,如 "my location_Locations/new york_City/city street_Address/200_MaxRecord/20_PageSize"

以上字符串包含类 SearchModel 的确切属性名称。现在我想做如下的事情:-

SearchModel model = new SearchModel();
string[] Parameters = "my location_Locations/new york_City/city street_Address/200_MaxRecord/20_PageSize".Split('/');
foreach (string item in Parameters)
{
string[] value=item.Split('_');
model.value[1] = value[0];
}

最佳答案

在你的类中添加以下代码

public class SearchModel
{
public object this[string propertyName]
{
get{
Type myType = typeof(MyClass);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set{
Type myType = typeof(SearchModel);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
switch (myPropInfo.PropertyType.Name)
{
case "Int32":
myPropInfo.SetValue(this, Convert.ToInt32(value), null);
break;
case "Int64":
myPropInfo.SetValue(this, Convert.ToInt64(value), null);
break;
case "Boolean":
myPropInfo.SetValue(this, Convert.ToBoolean(value), null);
break;
case "DateTime":
myPropInfo.SetValue(this, Convert.ToDateTime(value), null);
break;
case "String":
myPropInfo.SetValue(this, value.ToString(), null);
break;
default:
myPropInfo.SetValue(this, value, null);
break;
}
}
}
}

和你修改过的代码

SearchModel model = new SearchModel();
string[] Parameters = "my location_Locations/new york_City/city street_Address/200_MaxRecord/20_PageSize".Split('/');
foreach (string item in Parameters)
{
string[] value= item.Split('_');
// I changed this line
model[value[1]] = value[0];
}


SearchModel model = new SearchModel();
string[] Parameters = "my location_Locations/new york_City/city street_Address/200_MaxRecord/20_PageSize".Split('/');
foreach (string item in Parameters)
{
string[] value= item.Split('_');

PropertyInfo propertyInfo = model.GetType().GetProperty(value[1]);
propertyInfo.SetValue(model, Convert.ChangeType(value[0], propertyInfo.PropertyType),
}

不区分大小写:

model.GetType().GetProperty(value[1], BindingFlags.IgnoreCase |  BindingFlags.Public | BindingFlags.Instance )

关于c# - 动态绑定(bind)对象属性和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24800685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com