次のように、リフレクションを使用して特定のオブジェクト プロパティを設定するサード パーティのライブラリがあります。(これは簡易版です)
public void Set(object obj, string prop, object value) {
var propInf = obj.GetType().GetProperty(prop);
value = Convert.ChangeType(value, propInf.PropertyType);
propInf.SetValue(obj, value, null);
}
そして、null可能なプロパティを持つクラスがあります
class Test
{
public int? X { get; set; }
}
次のコードを書くと、変換できないと表示int
されますint?
var t = new Test();
Set(t, "X", 1);
Nullable は IConvertible を実装していないため、理にかなっています。次に、指定された値型のオブジェクトの null 許容バージョンを返すメソッドを作成することにしました。
public object MakeNullable(object obj) {
if(obj == null || !obj.GetType().IsValueType)
throw new Exception("obj must be value type!");
return Activator.CreateInstance(
typeof(Nullable<>).MakeGenericType(obj.GetType()),
new[] { obj });
}
この方法を次のように使用したいと考えました。
var t = new Test();
Set(t, "X", MakeNullable(1));
しかし、それはまだ変換できないと言っていint
ますint?
。typeof(Nullable<>).MakeGenericType(obj.GetType())
equalsをデバッグするint?
が、値をActivator.CreateInstace
返さない場合int
int?
これは私の場合です...助けはありますか?