我上课了
public class Car
{
public string Name {get;set;}
public int Year {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
在单独的代码中,我有一个字段名称作为字符串(让我们使用"年")作为一个例子.
我想做这样的事情
if (Car.HasProperty("Year"))
Run Code Online (Sandbox Code Playgroud)
这将弄清楚汽车对象上是否有一个Year字段.这将返回真实.
if (Car.HasProperty("Model"))
Run Code Online (Sandbox Code Playgroud)
将返回false.
我看到代码循环遍历属性,但想看看是否有更简洁的方法来确定是否存在单个字段.
Dav*_*d M 16
这种扩展方法应该这样做.
static public bool HasProperty(this Type type, string name)
{
return type
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Any(p => p.Name == name);
}
Run Code Online (Sandbox Code Playgroud)
如果要检查非实例属性,私有属性或其他选项,可以调整该BindingFlags语句中的值.您的使用语法不完全是您提供的.代替:
if (typeof(Car).HasProperty("Year"))
Run Code Online (Sandbox Code Playgroud)
由于您似乎只查找public属性,因此Type.GetProperty()可以完成以下任务:
if (typeof(Car).GetProperty("Year") != null) {
// The 'Car' type exposes a public 'Year' property.
}
Run Code Online (Sandbox Code Playgroud)
如果您想进一步抽象上面的代码,可以在以下代码上编写扩展方法Type class:
public static bool HasPublicProperty(this Type type, string name)
{
return type.GetProperty(name) != null;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
if (typeof(Car).HasPublicProperty("Year")) {
// The 'Car' type exposes a public 'Year' property.
}
Run Code Online (Sandbox Code Playgroud)
如果您还想检查是否存在非public属性,则必须调用带有参数的Type.GetProperties()的覆盖BindingFlags,并按照David M在其答案中所做的过滤结果.
| 归档时间: |
|
| 查看次数: |
8202 次 |
| 最近记录: |