3

これはpythonでは回答されているようですが、C#では回答されていません。

列挙型パラメーター (型) に基づいてクラス (タスク/タスク) のインスタンスからプロパティを取得し、そのプロパティをリストに追加しようとしています。トリッキーな部分は、プロパティ値が文字列になるのか文字列のリストになるのかがわからないことです。

だから、一般的に私は次のようなものを見ています:

PropertyInfo propertyInfo = typeof(Task).GetProperty(type.ToString());
List<string> values = new List<string>();

値がリストの場合、私が知っていることは機能しませんが、私の意図を示しています:

values.Add((string)propertyInfo.GetValue(task, null));

私のオプションは何ですか?

4

2 に答える 2

6

を使用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または、使用してキャストする代わりに、asnull に対して結果を使用してチェックできます。

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 要素を持つリストが必要な場合は、を使用する必要があります。例えば:nullPropertyType

if (propertyInfo.PropertyType == typeof(string))
{
    values.Add((string) propertyInfo.GetValue(task, null));
}
于 2013-01-02T20:47:23.137 に答える
5
PropertyInfo propertyInfo = typeof(Task).GetProperty(type.ToString());
List<string> values = new List<string>();

object p = propertyInfo.GetValue(task, null);
if(p is string)
{
    values.Add((string)p);
}
else if(p is List<string>)
{
    values.AddRange((List<string>)p);
}

または、次を使用できますas

string str = p as string;
List<string> list = p as List<string>;

if(str != null)
{
    values.Add(str);
}
else if(list != null)
{
    values.AddRange(list);
}
于 2013-01-02T20:48:24.717 に答える