How do i use Activator.CreateInstance with strings?

前端 未结 5 1960
礼貌的吻别
礼貌的吻别 2021-02-05 01:48

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();         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 02:15

    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 "".

    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);
    

提交回复
热议问题