将Type强制转换为类
本文关键字:转换 Type | 更新日期: 2023-09-27 18:09:03
如果我有一个这样定义的类:
public class className
{
public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}
public string Foo{ get; set; }
public string Bar { get; set; }
我当然可以这样设置和获取这些值:
className d = new className();
d["Foo"]="abcd" // set
string s = (string)f["Bar"];
(感谢Eduardo Cuomo的回答)
但是我真正想做的是:
Type target = Type.GetType(DocumentType);
// loop through list of key-value pairs and populate the data class defined in target object Type
foreach (Dictionary<string, string> PQList in LPQReq)
{
foreach (KeyValuePair<string, string> kvp in PQList)
{
// populate the member in the data class with the value from the MQ String
target[kvp.Key] = kvp.Value;
}
但是这不会编译成Cannot apply indexing with [] to an expression of type 'System.Type'
我该怎么做呢?
我当然可以使用dynamic
,但也许有一种方法将我的类型转换为我的目标类?
你可以用反射来做。假设所有可能的DocumentType
都有一个无参数构造函数,您可以这样做:
// Get the type (this comes from your example)
Type target = Type.GetType(DocumentType);
// Create an instance (that's the important part that was missing)
object instance = Activator.CreateInstance(target);
foreach (Dictionary<string, string> PQList in LPQReq) {
foreach (KeyValuePair<string, string> kvp in PQList) {
// This code again comes from your example,
// except propertyName is kvp.Key and value is kvp.Value
target.GetProperty(kvp.Key).SetValue(instance, kvp.Value, null);
}
}
为了访问索引器,您需要实例化该类型,并且需要将其强制转换为具有索引器的对象。
你可以定义一个接口:
public interface IIndexable_String
{
object this[string index]
{
get;
set;
}
}
应用到你的类中:
public class someclass : IIndexable_String
然后实例化实例并访问索引器
Type target = Type.GetType(DocumentType);
// Instantiate
IIndexable_String instance = (IIndexable_String)Activator.CreateInstance(target);
foreach (Dictionary<string, string> PQList in LPQReq)
{
foreach (KeyValuePair<string, string> kvp in PQList)
{
// populate the member in the data class with the value from the MQ String
instance[kvp.Key] = kvp.Value;
}
当然,如果您像@dasblinkenlight那样做,您甚至不需要类中神奇的getter和setter,也不需要接口。