36

在我的反射代码中,我的通用代码部分遇到了问题。特别是当我使用字符串时。

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.

我出于测试目的尝试了这个,它也出现在这个单衬里

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

本来我写的

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

但我得到这个错误

Additional information: No parameterless constructor defined for this object.

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

4

5 回答 5

49

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

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

因此,通过测试字符串大小写来解决您的问题:

var oType = oVal.GetType();
if (oType == typeof(string)) return oVal as string;
else return Activator.CreateInstance(oType, oVal);
于 2010-01-19T10:59:06.757 回答
5

您正在尝试这样做:

var sz = new string();

尝试编译它,您将了解您的错误。

您可以尝试:

var sz = Activator.CreateInstance(typeof(string), new object[] {"value".ToCharArray()});

但是看起来没什么用,应该直接用value...

于 2010-01-19T09:50:24.047 回答
2

看起来你正试图调用一个只接受一个字符串的构造函数——而且没有这样的构造函数。如果您已经有了一个字符串,为什么还要创建一个新字符串?(当你没有提供任何进一步的参数时,你试图调用一个无参数的构造函数——这同样不存在。)

请注意,这typeof(string)是获取对字符串类型的引用的更简单方法。

您能否向我们提供更多有关您正在尝试做的事情的更大图景的信息?

于 2010-01-19T09:51:23.887 回答
2

String 实际上没有将字符串作为输入的构造函数。有一个构造函数接受一个 char 数组,所以这应该可以工作:

var sz = Activator.CreateInstance ("".GetType (), "Test".ToCharArray ());
于 2010-01-19T09:54:34.973 回答
2

这是我在我的项目中使用的。至于需要创建一种对象的实例化并且在设计时不知道,这对我来说是很正常的。也许您正在循环访问对象属性,并且想要动态地实例化所有这些属性。我有很多次需要创建然后将值分配给非实例化的 POCO 对象......使用下面的代码,您可以使用存储在数据库中的字符串值来实例化对象或实例化存储在引用您的库中的对象库 - 所以你也可以绕过循环引用错误......希望它有所帮助。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;

/// <summary>
/// Instantiates an object. Must pass PropertyType.AssemblyQualifiedName for factory to operate
/// returns instantiated object
/// </summary>
/// <param name="typeName"></param>
/// <returns></returns>
public static object Create(string typeAssemblyQualifiedName)
{
  // resolve the type
  Type targetType = ResolveType(typeAssemblyQualifiedName);
  if (targetType == null)
    throw new ArgumentException("Unable to resolve object type: " + typeAssemblyQualifiedName);

  return Create(targetType);
}

/// <summary>
/// create by type of T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Create<T>()
{
  Type targetType = typeof(T);
  return (T)Create(targetType);
}

/// <summary>
/// general object creation
/// </summary>
/// <param name="targetType"></param>
/// <returns></returns>
public static object Create(Type targetType)
{
  //string test first - it has no parameterless constructor
  if (Type.GetTypeCode(targetType) == TypeCode.String)
    return string.Empty;

  // get the default constructor and instantiate
  Type[] types = new Type[0];
  ConstructorInfo info = targetType.GetConstructor(types);
  object targetObject = null;

  if (info == null) //must not have found the constructor
    if (targetType.BaseType.UnderlyingSystemType.FullName.Contains("Enum"))
      targetObject = Activator.CreateInstance(targetType);
    else
      throw new ArgumentException("Unable to instantiate type: " + targetType.AssemblyQualifiedName + " - Constructor not found");
  else
    targetObject = info.Invoke(null);

  if (targetObject == null)
    throw new ArgumentException("Unable to instantiate type: " + targetType.AssemblyQualifiedName + " - Unknown Error");
  return targetObject;
}

/// <summary>
/// Loads the assembly of an object. Must pass PropertyType.AssemblyQualifiedName for factory to operate
/// Returns the object type.
/// </summary>
/// <param name="typeString"></param>
/// <returns></returns>
public static Type ResolveType(string typeAssemblyQualifiedName)
{
  int commaIndex = typeAssemblyQualifiedName.IndexOf(",");
  string className = typeAssemblyQualifiedName.Substring(0, commaIndex).Trim();
  string assemblyName = typeAssemblyQualifiedName.Substring(commaIndex + 1).Trim();

  if (className.Contains("[]"))
    className.Remove(className.IndexOf("[]"), 2);

  // Get the assembly containing the handler
  Assembly assembly = null;
  try
  {
    assembly = Assembly.Load(assemblyName);
  }
  catch
  {
    try
    {
      assembly = Assembly.LoadWithPartialName(assemblyName);//yes yes this is obsolete but it is only a backup call
    }
    catch
    {
      throw new ArgumentException("Can't load assembly " + assemblyName);
    }
  }

  // Get the handler
  return assembly.GetType(className, false, false);
}
于 2015-06-30T02:58:15.403 回答