28 .net c# reflection activator
在我的反射代码中,我遇到了我的通用代码部分的问题.特别是当我使用一个字符串.
var oVal = (object)"Test";
var oType = oVal.GetType();
var sz = Activator.CreateInstance(oType, oVal);
Run Code Online (Sandbox Code Playgroud)
例外
An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dll
Additional information: Constructor on type 'System.String' not found.
Run Code Online (Sandbox Code Playgroud)
我试过这个用于测试目的,它也发生在这个单一的衬里
var sz = Activator.CreateInstance("".GetType(), "Test");
Run Code Online (Sandbox Code Playgroud)
我最初写的
var sz = Activator.CreateInstance("".GetType());
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误
Additional information: No parameterless constructor defined for this object.
Run Code Online (Sandbox Code Playgroud)
如何使用反射创建字符串?
Han*_*ant 42
请记住,字符串类是不可变的.创建后无法更改.这就解释了为什么它没有无参数构造函数,它永远不会生成除空字符串之外的有用字符串对象.这已经在C#语言中提供,它是"".
相同的推理适用于string(String)构造函数.重复一个字符串是没有意义的,你传递给构造函数的字符串已经是一个非常好的字符串实例.
因此,通过测试字符串大小写来修复您的问题:
var oType = oVal.GetType();
if (oType == typeof(string)) return oVal as string;
else return Activator.CreateInstance(oType, oVal);
Run Code Online (Sandbox Code Playgroud)
你正试图这样做:
var sz = new string();
Run Code Online (Sandbox Code Playgroud)
尝试编译它,你就会明白你的错误.
你可以尝试:
var sz = Activator.CreateInstance(typeof(string), new object[] {"value".ToCharArray()});
Run Code Online (Sandbox Code Playgroud)
但它看起来没用,你应该直接使用价值......
归档时间: |
|
查看次数: |
31928 次 |
最近记录: |