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

5

あなたはこれをやろうとしています:

var sz = new string();

コンパイルしてみてください。エラーを理解できます。

あなたは試すことができます:

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

しかし、それは役に立たないように見えます。値を直接使用する必要があります...

于 2010-01-19T09:50:24.047 に答える
2

文字列を取るだけのコンストラクターを呼び出そうとしているようですが、そのようなコンストラクターはありません。既に文字列を取得している場合、なぜ新しい文字列を作成しようとしているのでしょうか? (これ以上引数を指定しなかった場合は、パラメーターなしのコンストラクターを呼び出そうとしていましたが、これも存在しません。)

typeof(string)文字列型への参照を取得する簡単な方法であることに注意してください。

あなたがやろうとしていることの全体像について、より多くの情報を提供していただけますか?

于 2010-01-19T09:51:23.887 に答える
2

これは私がプロジェクトで使用するものです。オブジェクトのタイプのインスタンス化を作成する必要があり、設計時にわからないことは、私にとってはむしろ普通のことです。おそらく、オブジェクトのプロパティを循環していて、それらすべてを動的にインスタンス化したいと思うでしょう。インスタンス化されていないPOCOオブジェクトを作成してから値を割り当てる必要が何度もありました...以下のコードを使用すると、DBに保存されている文字列値を使用して、オブジェクトをインスタンス化するか、ライブラリに保存されているオブジェクトをインスタンス化できます。ライブラリ - 循環参照エラーも回避できるようにします...お役に立てば幸いです。

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 に答える
2

String には実際には、文字列を入力として受け取るコンストラクターはありません。char 配列を取るコンストラクターがあるため、これは機能するはずです。

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