我想通过仅用字符串识别对象来获得List中某项的值
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Personalization Test" verbose="1">
<listeners>
<listener class-name="util.InvokedMethodListener"/>
</listeners>
<test name="Add Device" >
<groups>
<run>
<include name="startAppiumServer"/>
<include name="startApp_reset"/>
<include name="welcome"/>
<include name="tnc"/>
<include name="permission"/>
<include name="login"/>
<include name="dashboard"/>
</run>
</groups>
<classes>
<class name="test_cases.StartServer"/>
<class name="test_cases.WelcomeTest"/>
<class name="test_cases.TermAndConditionTest"/>
<class name="test_cases.PermissionTest"/>
</classes>
</test>
</suite>
string A ="some_string";
listobject.Add(fruit[0].A);
它不接受listobject.Add(fruit [0] .A);作为标识符
答案 0 :(得分:0)
从技术上讲,您可以尝试使用 Reflection ,即按其名称查找属性:
using System.Reflection;
...
private static T PropertyReader<T>(object value, string name) {
if (null == value)
throw new ArgumentNullException(nameof(value));
else if (null == name)
throw new ArgumentNullException(nameof(name));
var prop = value.GetType().GetProperty(name);
if (null == prop || !prop.CanRead)
throw new ArgumentException($"property {name} has not been found.", nameof(name));
return (T)(Convert.ChangeType(prop.GetValue(value, new object[0]), typeof(T)));
}
然后您可以按以下方式使用它:
listobject.Add(PropertyReader<string>(fruit[0], A));