どのように判定するかは目的や用途に応じて変わりそうですが、あくまで例としてサンプルを作成してみました。
環境
- Visual Studio 2017
- .NET Core 2.2
サンプルコード
public static void Main()
{
var personClass = new PersonClass();
var personStruct = new PersonStruct();
var persons = new List<PersonClass>();
IsNullable(typeof(int));// False
IsNullable(typeof(int?));// True
IsNullable(typeof(PersonClass));// True
IsNullable(typeof(PersonStruct));// False
IsNullable(personClass.GetType());// True
IsNullable(personClass.Age.GetType());// False
IsNullable(personClass.Name?.GetType());// True
IsNullable(personStruct.GetType());// False
IsNullable(personStruct.Age.GetType());// False
IsNullable(personStruct.Name?.GetType());// True
IsNullable(typeof(List<>));// True
IsNullable(persons.GetType());// True
}
static bool IsNullable(Type type)
{
var ret =
type == null || // Null条件演算子用にこの条件を入れているだけなので、場合によっては不要
!type.IsValueType || // 値型でない -> Nullable
Nullable.GetUnderlyingType(type) != null;// 非Null許容型が取得できる -> Null許容演算子が指定されている -> Nullable
Console.WriteLine(ret);// デバッグ用に表示
return ret;
}
public class PersonClass
{
public int Age { get; set; }
public string Name { get; set; }
}
public struct PersonStruct
{
public int Age { get; set; }
public string Name { get; set; }
}
間違いや他に良い方法があれば教えてください。