私は次の設定をしています:
public class Child<T>: BaseClass
{
public T Value;
}
public class IntChild: Child<int> { }
public class BoolChild: Child<bool> { }
public class FloatChild: Child<float> { }
public class MyProgram
{
public BaseClass Source;
public void SetValue(object val)
{
// I want to do something like the following
// ((Child) Source).Value = (val.GetType()) val;
// Instead, I have to do it like this
string temp = val.ToString();
switch (Source.GetType())
{
case "IntChild":
((IntChild) Source).Value = int.Parse(val.ToString());
break;
case "BoolChild":
((BoolChild) Source).Value = bool.Parse(val.ToString());
break;
case "FloatChild":
((FloatChild) Source).Value = float.Parse(val.ToString());
break;
}
}
}
BaseClassを変更できません(ToString()を上書きすることしかできませんでした)。
スイッチをより単純なコード行に置き換えるにはどうすればよいですか?次のようなことをしたい
((Child) Source).Value = (val.GetType()) val;
、スイッチの代わりに。これも可能ですか?
SlavaUtesinovによってすでに提供されている回答の小さなバリエーション
// Only set value if implementation of Child<>.
// If any other derived class of BaseClass with value field, then dont set
if(source.GetType().BaseType != null
&& source.GetType().BaseType.IsGenericType
&& source.GetType().BaseType.GetGenericTypeDefinition() == typeof(Child<>))
{
Console.WriteLine("Is implementation of Child<>");
source.GetType().GetField("Value").SetValue(source, val);
}
else
{
Console.WriteLine("Not implementation of Child<>");
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加