私は、あるクラスのプロパティがnullかどうかを調べることを目的とする小さなメソッドを作成しました。プロパティがnullの場合は、新しいインスタンスを作成します。私は実際に値を設定しています一部の上に立ち往生しています:C#リフレクション、ヌルプロパティの新しいインスタンスを設定する
public static void CheckIfPropertyIsNull<TEntity>(SomeBusinessEntity someBusinessEntity) where TEntity : new()
{
var properties = typeof(SomeBusinessEntity).GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
Type currentType = propertyInfo.PropertyType;
if (currentType == typeof(TEntity))
{
var propertyData = propertyInfo.GetValue(someBusinessEntity, null);
if (propertyData == null)
{
object instance = Activator.CreateInstance(typeof(TEntity));
// And then?
//propertyInfo.SetValue(null, instance);
return;
}
}
}
}
私はのSetValue()メソッドを使用しようとしたが運で。
あなたが提供しているタイプにパラメータのないコンストラクタがあるというジェネリックスシステムからの要求に煩わされました。なぜなら、 'Activator.CreateInstance(...)'ではなく 'new TEntity() ? –
私はいくつかの思考プロセスを持ち、コードをちょうど落書きしていました。私は以前に新しいTEntity()を使用していました。 –