我有一个自定义类的列表(其中包含Name,Age,Address等属性)。如何在自定义类列表中检查是否有名为“Name”的属性。我不想检查属性名称是否存在项目,而是我想检查属性是否存在。
对此有何帮助?
答案 0 :(得分:8)
如果您有一个名为Foo
的类,并且想要检查属性Bar
是否存在,则可以使用反射执行以下操作:
bool barExists = typeof(Foo).GetProperties()
.Where(x => x.Name == "Bar")
.Any();
或更短甚至(感谢提醒@Adam Robinson):
bool barExists = typeof(Foo).GetProperties().Any(x => x.Name == "Bar")
答案 1 :(得分:2)
if(typeof(CustomClass).GetProperties().Where(i => i.Name == FieldYoureLookingFor).Count() > 0)
{
DoSomething();
}
答案 2 :(得分:1)
这里有一个对象扩展方法,它告诉您给定的PropertyName是否存在于任何给定的对象中。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StackOverflow.MyExtensions
{
public static class ObjectExtentions
{
public static Boolean PropertyExists(this object Object, string PropertyName)
{
var ObjType = Object.GetType();
var TypeProperties = ObjType.GetProperties();
Boolean PropertyExists = TypeProperties
.Where(x => x.Name == PropertyName)
.Any();
return PropertyExists;
}
}
}
这是一个使用示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StackOverflow.MyExtensions;
namespace StackOverflow
{
class Person
{
string _FirstName; // FirstName
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName;
}
class Program
{
static void Main(string[] args)
{
Person SamplePerson = new Person();
if (SamplePerson.PropertyExists("FirstName"))
Console.WriteLine("Yes! Property does exist!");
else
Console.WriteLine("Nope, property does not exist on object SamplePerson");
if (SamplePerson.PropertyExists("LastName"))
Console.WriteLine("Yes! Property does exist!");
else
Console.WriteLine("Nope, property does not exist on object SamplePerson");
}
}
}
干杯