看起来这已经回答了python,但不是C#,因为我是蟒蛇文盲和新的C#,这里有:
我正在尝试从基于枚举参数(类型)的类(任务/任务)的实例获取属性,并将该属性添加到List.棘手的部分是我不确定属性值是字符串还是字符串列表.
所以,一般来说我看的是:
PropertyInfo propertyInfo = typeof(Task).GetProperty(type.ToString());
List<string> values = new List<string>();
Run Code Online (Sandbox Code Playgroud)
当值是List时,我知道的东西不起作用,但说明了我的意图:
values.Add((string)propertyInfo.GetValue(task, null));
Run Code Online (Sandbox Code Playgroud)
我有什么选择?
您可以使用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...
}
Run Code Online (Sandbox Code Playgroud)
或者代替使用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...
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果属性是任何其他类型的字符串序列,而不仅仅是a,则此方法有效List<string>.它还复制列表,以便任何进一步的更改不会影响属性引用的现有列表.如果你需要调整:)
Lee的答案提醒我一点 - 如果它是一个string具有null值的属性,并且您想要一个包含单个null元素的列表,则需要使用PropertyType.例如:
if (propertyInfo.PropertyType == typeof(string))
{
values.Add((string) propertyInfo.GetValue(task, null));
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)