0

ジェネリック型のすべてのパブリックプロパティを初期化したい。
私は次のメソッドを書きました:

public static void EmptyModel<T>(ref T model) where T : new()
{
    foreach (PropertyInfo property in typeof(T).GetProperties())
    {
        Type myType = property.GetType().MakeGenericType();
        property.SetValue(Activator.CreateInstance(myType));//Compile error
    }
}

しかし、コンパイルエラーがあります

どうすればいいですか?

4

1 に答える 1

5

ここには3つの問題があります。

  • PropertyInfo.SetValue2つの引数を取ります。1つはプロパティを設定する(またはnull静的プロパティの)オブジェクトへの参照で、もう1つは設定する値です。
  • property.GetType()を返しPropertyInfoます。プロパティ自体のタイプを取得するには、property.PropertyType代わりに使用します。
  • プロパティタイプにパラメーターなしのコンストラクターがない場合、コードはケースを処理しません。ここでは、作業方法を根本的に変更せずに凝りすぎることはできないため、私のコードでは、nullパラメーターのないコンストラクターが見つからない場合にプロパティを初期化します。

私はあなたが探しているのはこれだと思います:

public static T EmptyModel<T>(ref T model) where T : new()
{
    foreach (PropertyInfo property in typeof(T).GetProperties())
    {
        Type myType = property.PropertyType;
        var constructor = myType.GetConstructor(Type.EmptyTypes);
        if (constructor != null)
        {
            // will initialize to a new copy of property type
            property.SetValue(model, constructor.Invoke(null));
            // or property.SetValue(model, Activator.CreateInstance(myType));
        }
        else
        {
            // will initialize to the default value of property type
            property.SetValue(model, null);
        }
    }
}
于 2013-03-26T03:02:23.700 に答える