C# 如何搜索对象是否具有值为C的属性#
我想创建一个函数,我可以在其中传入任意对象,并检查它是否具有具有特定值的特定属性。我试图用反射来做这件事,但是反射仍然让我有点困惑。我希望有人能给我指出正确的方向 下面是我正在尝试的代码,但显然它不起作用:C# 如何搜索对象是否具有值为C的属性#,c#,reflection,C#,Reflection,我想创建一个函数,我可以在其中传入任意对象,并检查它是否具有具有特定值的特定属性。我试图用反射来做这件事,但是反射仍然让我有点困惑。我希望有人能给我指出正确的方向 下面是我正在尝试的代码,但显然它不起作用: public static bool PropertyHasValue(object obj, string propertyName, string propertyValue) { try { if(obj.GetType().GetPropert
public static bool PropertyHasValue(object obj, string propertyName, string propertyValue)
{
try
{
if(obj.GetType().GetProperty(propertyName,BindingFlags.Instance).GetValue(obj, null).ToString() == propertyValue)
{
Debug.Log (obj.GetType().FullName + "Has the Value" + propertyValue);
return true;
}
Debug.Log ("No property with this value");
return false;
}
catch
{
Debug.Log ("This object doesnt have this property");
return false;
}
}
检索成员时,除了指定实例/静态外,还必须指定公共/非公共: 例如,要检索公共属性,您将使用:
GetProperty(propertyName,BindingFlags.Instance | BindingFlags.Public)
要检索所有属性,必须同时检索Public和NonPublic。您需要在
Type.GetProperty
方法调用中指定更多的BindingFlags
。您可以使用|
字符和其他标志(例如BindingFlags.Public
)来执行此操作。其他问题是不检查来自PropertyInfo.GetValue
调用的nullobj
参数或null结果
为了使方法更加明确,您可以这样编写,并在您认为合适的地方折叠
public static bool PropertyHasValue(object obj, string propertyName, string propertyValue)
{
try
{
if(obj != null)
{
PropertyInfo prop = obj.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
if(prop != null)
{
object val = prop.GetValue(obj,null);
string sVal = Convert.ToString(val);
if(sVal == propertyValue)
{
Debug.Log (obj.GetType().FullName + "Has the Value" + propertyValue);
return true;
}
}
}
Debug.Log ("No property with this value");
return false;
}
catch
{
Debug.Log ("An error occurred.");
return false;
}
}
在我看来,您应该接受propertyValue
作为对象
,并平等地比较对象,但这将显示出与原始示例不同的行为。您应该查看并阅读有关绑定标志的内容。具体而言:
您必须指定Instance或Static以及Public或NonPublic,否则将不返回任何成员。在这里回答这个问题太晚了。但是我在寻找同样的问题,并用
LINQ
和反射
以更干净的方式解决了它。因此,如果您对LINQ
开放。你可以这样得到它
String propertyValue = "Value_to_be_compared";
Bool Flag = YourObject.GetType().GetProperties().Any(t => t.GetValue(objEmailGUID, null).ToString().Contains(propertyValue));
if(Flag)
{
//spread love if true
}
代码将检查您的任何属性是否反对对值进行比较
如果要匹配精确值,则可以选择:
Bool Flag = YourObject.GetType().GetProperties().Any(t => t.GetValue(objEmailGUID, null).ToString() == propertyValue);
什么“不起作用”?你有错误吗?@MichaelTaylor3D不只是打印出有错误,你实际上应该捕获特定的执行选项并记录异常的详细信息,这样你就知道出了什么问题(或者更好的是,如果你不能正确处理它,就根本不捕获异常)。仅供参考,如果您试图在安全运行时(比如Silverlight)上查找非公共属性,则不会得到任何。即使使用反射,Silverlight运行时也会阻止您获取非公共成员。或者更好:继续使用
GetProperty
,但检查其输出是否为null
(未找到属性)或PropertyInfo
实例。@MichaelTaylor3D捕获异常不是执行流控制的正确方法。速度太慢了。请参阅:如果属性是非公共的,反射仍然可以获取该属性。他可能想这样做,但我不认为这是它不起作用的原因。绑定标志限制了结果,所以将它们一起删除,您将获得实例。指定实例时,您还必须指定公共或非公共。这就是它的工作方式。请参见此处的示例()和此处的文档()。谢谢@Flyingstrudel,我找不到。