c# では、何か他のことをする前に、List が保持している型を判断できますか? 例:
List<int> listing = new List<int>();
if(listing is int)
{
// if List use <int> type, do this...
}
else if(listing is string)
{
// if List use <string> type, do this...
}
メソッドを使用できますType.GetGenericArguments()
。
お気に入り:
Type[] types = list.GetType().GetGenericArguments();
if (types.Length == 1 && types[0] == typeof(int))
{
...
}
オブジェクト指向言語で c# としてコーディングする場合、通常、実行時の型で条件を使用するよりもポリモーフィズムを使用することを好みます。次回はこのようなものを試してみて、気に入るかどうか見てみましょう!
interface IMyDoer
{
void DoThis();
}
class MyIntDoer: IMyDoer
{
private readonly List<int> _list;
public MyIntClass(List<int> list) { _list = list; }
public void DoThis() { // Do this... }
}
class MyStringDoer: IMyDoer
{
private readonly List<string> _list;
public MyIntClass(List<string> list) { _list = list; }
public void DoThis() { // Do this... }
}
次のように呼び出します。
doer.DoThis(); // Will automatically call the right method
//depending on the runtime type of 'doer'!
コードが短くなり、簡潔になり、if ステートメントでジャングルを使用する必要がなくなります。
このコードの配置 (または因数分解) の方法により、コードを壊すことなく内部構造を自由に変更できます。条件付きを使用すると、たとえば無関係な問題を修正するときに、コードが簡単に壊れることがわかります。これは、コードの非常に貴重なプロパティです。これがお役に立てば幸いです。