型が「単純な」型であるかどうかはどうすればわかりますか? つまり、単一の値を保持するかどうかです。質問する

型が「単純な」型であるかどうかはどうすればわかりますか? つまり、単一の値を保持するかどうかです。質問する
typeof(string).IsPrimitive == false
typeof(int).IsPrimitive == true
typeof(MyClass).IsClass == true
typeof(string).IsClass == true
typeof(string).IsByRef == false
typeof(MyClass).IsByRef == true // correction: should be false (see comments below)

T の新しいインスタンスをインスタンス化し、それが「複雑な」クラスである場合は、ソース データ値のセットからそのプロパティを入力するメソッドがあります。

(a) T が単純な型 (文字列や int など) である場合、ソース データから T への迅速な変換が実行されます。

(b) T がクラス (ただし、文字列のような単純なものではない) である場合は、Activator.CreateInstance を使用し、少しのリフレクションを実行してフィールドに入力します。

メソッド (a) とメソッド (b) のどちらを使用する必要があるかをすばやく簡単に判断する方法はありますか? このロジックは、T を型引数として持つジェネリック メソッド内で使用されます。

ベストアンサー1

文字列はおそらく特殊なケースです。

私ならそうすると思います.....

bool IsSimple(Type type)
{
    return type.IsPrimitive 
      || type.Equals(typeof(string));
}

編集:

場合によっては、列挙型や小数点数などのケースをさらにカバーする必要があります。列挙型は C# の特殊な型です。小数点は他の型と同様に構造体です。構造体の問題は、複雑になる可能性があり、ユーザー定義型である場合や、単なる数値である場合があることです。そのため、区別するには、それらを知る以外に方法はありません。

bool IsSimple(Type type)
{
  return type.IsPrimitive 
    || type.IsEnum
    || type.Equals(typeof(string))
    || type.Equals(typeof(decimal));
}

null 許容型の対応物の取り扱いも少し注意が必要です。null 許容型自体は構造体です。

bool IsSimple(Type type)
{
  if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
  {
    // nullable type, check if the nested type is simple.
    return IsSimple(type.GetGenericArguments()[0]);
  }
  return type.IsPrimitive 
    || type.IsEnum
    || type.Equals(typeof(string))
    || type.Equals(typeof(decimal));
}

テスト:

Assert.IsTrue(IsSimple(typeof(string)));
Assert.IsTrue(IsSimple(typeof(int)));
Assert.IsTrue(IsSimple(typeof(decimal)));
Assert.IsTrue(IsSimple(typeof(float)));
Assert.IsTrue(IsSimple(typeof(StringComparison)));  // enum
Assert.IsTrue(IsSimple(typeof(int?)));
Assert.IsTrue(IsSimple(typeof(decimal?)));
Assert.IsTrue(IsSimple(typeof(StringComparison?)));
Assert.IsFalse(IsSimple(typeof(object)));
Assert.IsFalse(IsSimple(typeof(Point)));  // struct in System.Drawing
Assert.IsFalse(IsSimple(typeof(Point?)));
Assert.IsFalse(IsSimple(typeof(StringBuilder))); // reference type

.NET Core に関する注意

DucoJが指摘しているように彼の答えType使用されているメソッドの一部は、 .NET Core のクラスでは使用できなくなりました。

コードを修正しました (動作することを願っていますが、自分で試すことができませんでした。動作しない場合はコメントしてください):

bool IsSimple(Type type)
{
  var typeInfo = type.GetTypeInfo();
  if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>))
  {
    // nullable type, check if the nested type is simple.
    return IsSimple(typeInfo.GetGenericArguments()[0]);
  }
  return typeInfo.IsPrimitive 
    || typeInfo.IsEnum
    || type.Equals(typeof(string))
    || type.Equals(typeof(decimal));
}

おすすめ記事