Rem*_*us 0 .net c# reflection casting
我想知道是否有一种方法可以使用system.reflection转换为精确类型,这样你就可以避免进行显式转换
(System.DateTime)
Run Code Online (Sandbox Code Playgroud)
例如
假设我有一个像这样的词典
Dictionary<propName, Dictionary<object, Type>>
Run Code Online (Sandbox Code Playgroud)
并假设我迭代一个对象道具列表
foreach (var prop in @object.GetType().GetProperties())
{
object propValue = propInfo.GetValue(@object, null);
string propName = propInfo.Name;
Dictionary<object, Type> typeDictionary = new Dictionary<object, Type>();
Type propType = propInfo.GetValue(@object, null).GetType();
typeDictionary[propValue ] = propType ;
propsDictionary[propInfo.Name] = propValue;
}
Run Code Online (Sandbox Code Playgroud)
我想做类似的事情,使用类似的东西投射到精确类型
// this part is only for guidelines
// it should obtain the exact Type
// ... but it returns a string of that type Namespace.Type
Type exactType = Dictionary[enumOfPropName][someValue]
// this part should know the exact type Int32 for example and cast to exact
var propX = (exactType)someValue
Run Code Online (Sandbox Code Playgroud)
有没有办法做这样的事情,如果是这样,我怎么能得到这个?此外大部分代码只是一个指南,一个想法,所以请不要采取它.谢谢你们.
这里的结论是,不可能有一个与任意对象实例的确切类型匹配的静态类型变量,因为这样做将需要尚未提供的信息.
作为一种解决方法,请考虑制作变量dynamic,并从那里看看你能做些什么.
| 归档时间: |
|
| 查看次数: |
1946 次 |
| 最近记录: |