を使用PropertyInfo.PropertyType
してプロパティのタイプを確認できます。または、値を取得してobject
そこから移動することもできます。
List<string> values = new List<string>();
object value = propertyInfo.GetValue(task, null);
if (value is string)
{
values.Add((string) value);
}
else if (value is IEnumerable<string>)
{
values.AddRange((IEnumerable<string>) value);
}
else
{
// Do whatever you want if the type doesn't match...
}
is
または、使用してキャストする代わりに、as
null に対して結果を使用してチェックできます。
List<string> values = new List<string>();
object value = propertyInfo.GetValue(task, null);
string stringValue = value as string;
if (stringValue != null)
{
values.Add(stringValue);
}
else
{
IEnumerable<string> valueSequence = value as IEnumerable<string>;
if (valueSequence != null)
{
values.AddRange(valueSequence);
}
else
{
// Do whatever you want if the type doesn't match...
}
}
これは、プロパティがList<string>
. また、プロパティが参照する既存のリストにそれ以上の変更が影響しないように、リストもコピーします。必要に応じて調整してください:)
Lee の回答で思い出した点が 1 つあります。それが値を持つプロパティでstring
あり、単一の null 要素を持つリストが必要な場合は、を使用する必要があります。例えば:null
PropertyType
if (propertyInfo.PropertyType == typeof(string))
{
values.Add((string) propertyInfo.GetValue(task, null));
}