因此,我想返回对象的属性,例如通用或硬编码的typeof(User),例如
但是,我只想返回我要为其获取属性的对象的属性,并为其设置了一个值,而不是默认值或null。这样做的原因是,我只能使用这些属性来构建表达式,以仅针对数据库中项目的列检查这些属性。
我尝试过类似的方法,但是它仍然可以带回所有价值,
public User AutomatedUser {get;set;} // some properties of this will populated elsewhere
var props = typeof(User).GetProperties()
.Where(pi => pi.GetValue(AutomatedFromUser) != pi.PropertyType.GetDefault());
然后,我在论坛上找到了用于获取类型默认值的方法,因为编译器不允许!= default(pi.PropertyType),因为“ Pi”是变量。方法如下...
public static object GetDefault(this Type type)
{
// If no Type was supplied, if the Type was a reference type, or if the Type was a System.Void, return null
if (type == null || !type.IsValueType || type == typeof(void))
return null;
// If the supplied Type has generic parameters, its default value cannot be determined
if (type.ContainsGenericParameters)
throw new ArgumentException(
"{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe supplied value type <" + type +
"> contains generic parameters, so the default value cannot be retrieved");
// If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct), return a
// default instance of the value type
if (type.IsPrimitive || !type.IsNotPublic)
{
try
{
return Activator.CreateInstance(type);
}
catch (Exception e)
{
throw new ArgumentException(
"{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe Activator.CreateInstance method could not " +
"create a default instance of the supplied value type <" + type +
"> (Inner Exception message: \"" + e.Message + "\")", e);
}
}
// Fail with exception
throw new ArgumentException("{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe supplied value type <" + type +
"> is not a publicly-visible type, so the default value cannot be retrieved");
}
}
任何提示或帮助,将不胜感激,为什么这将无法正常工作,或我要去哪里错了。
您遇到的问题与装箱和==
执行引用相等的事实有关。两者PropertyInfo.GetValue
和您的GetDefault
函数都返回object
,因此您的值类型将被装箱。这意味着即使两个值均为零,也将它们放入两个单独的框中。这些框中的每个框都不相同object
,因此引用相等返回false
。
考虑以下:
object x = 0;
object y = 0;
Console.WriteLine(x == y); // prints False
解决方案是改为调用object.Equals
(实例或静态版本)。
object x = 0;
object y = 0;
Console.WriteLine(x.Equals(y)); // prints True
Console.WriteLine(object.Equals(x, y)); // prints True
有关这两个版本的示例,请参见此SharpLab演示。
这意味着您的问题的解决方案如下:
var props = typeof(User).GetProperties()
.Where(pi =>
!object.Equals(
pi.GetValue(AutomatedFromUser),
pi.PropertyType.GetDefault()
)
);
null
因为null.Equals(...)
显然会抛出异常,所以我们使用静态版本来防范。调用静态方法与实例方法相同,不同之处在于它首先检查引用是否相等,然后防止出现空值。之后它调用x.Equals(y)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句