如何将Activator.CreateInstance与字符串一起使用? [英] How do i use Activator.CreateInstance with strings?

查看:297
本文介绍了如何将Activator.CreateInstance与字符串一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的反射代码中,我的通用部分遇到了问题。

In my reflection code i hit a problem with my generic section of code. Specifically when i use a string.

var oVal = (object)"Test";
var oType = oVal.GetType();
var sz = Activator.CreateInstance(oType, oVal);

例外

An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dll

Additional information: Constructor on type 'System.String' not found.

我出于测试目的进行了尝试,并且它也出现在单个衬里中

I tried this for testing purposes and it occurs in this single liner too

var sz = Activator.CreateInstance("".GetType(), "Test");

我最初写过

var sz = Activator.CreateInstance("".GetType());

但我收到此错误

Additional information: No parameterless constructor defined for this object.

如何使用反射创建字符串?

How do i create a string using reflection?

推荐答案

请记住,字符串类是不可变的。创建后无法更改。这就解释了为什么它没有无参数的构造函数,除了空字符串之外,它永远无法生成有用的字符串对象。

Keep in mind that the string class is immutable. It cannot be changed after it is created. That explains why it doesn't have a parameterless constructor, it could never generate a useful string object other than an empty string. That's already available in the C# language, it is "".

相同的推理适用于string(String)构造函数。复制一个字符串没有任何意义,您传递给构造函数的字符串已经是该字符串的一个很好的实例。

Same reasoning applies for a string(String) constructor. There is no point in duplicating a string, the string you'd pass to the constructor is already a perfectly good instance of the string.

因此,通过测试以下内容来解决问题字符串大小写:

So fix your problem by testing for the string case:

var oType = oVal.GetType();
if (oType == typeof(string)) return oVal as string;
else return Activator.CreateInstance(oType, oVal);

这篇关于如何将Activator.CreateInstance与字符串一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆