C# 确定是否可以为反射特性指定给定值
确定反射特性是否可以指定给定值的最简单方法是什么 我需要的方法签名是:C# 确定是否可以为反射特性指定给定值,c#,.net,reflection,C#,.net,Reflection,确定反射特性是否可以指定给定值的最简单方法是什么 我需要的方法签名是: public static bool IsAssignable(PropertyInfo property, object value) { throw new NotImplementedException(); } 此方法应适用于值类型和引用类型,并且weither值是否为null 谢谢你们的帮助 Manitra.您可能正在查找您可能正在查找您无法确定作为对象传递的null的类型。您只能说该属性
public static bool IsAssignable(PropertyInfo property, object value)
{
throw new NotImplementedException();
}
此方法应适用于值类型和引用类型,并且weither值是否为null
谢谢你们的帮助
Manitra.您可能正在查找您可能正在查找您无法确定作为
对象传递的null
的类型。您只能说该属性是否能够接受null
因此,可以采用编译时类型:
public static bool IsAssignable<T>(PropertyInfo property, T value)
{
if (value != null)
{
return property.PropertyType.IsAssignableFrom(value.GetType());
}
return property.PropertyType.IsAssignableFrom(typeof(T));
}
公共静态bool可分配(PropertyInfo属性,T值)
{
if(值!=null)
{
返回property.PropertyType.IsAssignableFrom(value.GetType());
}
返回property.PropertyType.IsAssignableFrom(typeof(T));
}
您无法确定作为对象传递的null
的类型。您只能说该属性是否能够接受null
因此,可以采用编译时类型:
public static bool IsAssignable<T>(PropertyInfo property, T value)
{
if (value != null)
{
return property.PropertyType.IsAssignableFrom(value.GetType());
}
return property.PropertyType.IsAssignableFrom(typeof(T));
}
公共静态bool可分配(PropertyInfo属性,T值)
{
if(值!=null)
{
返回property.PropertyType.IsAssignableFrom(value.GetType());
}
返回property.PropertyType.IsAssignableFrom(typeof(T));
}
感谢Stefan和John的回答,以及“确定反射属性是否可以分配为null”问题,以下是我将使用的代码:
public static bool IsAssignable(PropertyInfo property, object value)
{
if (value == null && property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) == null)
return false;
if (value != null && !property.PropertyType.IsAssignableFrom(value.GetType()))
return false;
return true;
}
这适用于所有情况,并且以一种纯粹的松散类型的方式
Manitra.感谢Stefan和John的回答,以及“确定反射属性是否可以分配为null”问题,以下是我将使用的代码:
public static bool IsAssignable(PropertyInfo property, object value)
{
if (value == null && property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) == null)
return false;
if (value != null && !property.PropertyType.IsAssignableFrom(value.GetType()))
return false;
return true;
}
这适用于所有情况,并且以一种纯粹的松散类型的方式
曼尼特拉。好的,谢谢。但是如果该值为null,并且我不能对其调用GetType(),那么好的,谢谢。但是如果该值为null,我就不能对其调用GetType()?感谢您的回答,这在强类型用例中是正确的(向上投票)。在我的例子中,我确实有一个对象作为值,所以我不能使用typeof(t)。但是,事实上,我发现了一个类似的问题,它处理空值,所以没问题。感谢这个答案,它在强类型用例(向上投票)中是正确的。在我的例子中,我确实有一个对象作为值,所以我不能使用typeof(t)。但是,事实上,我发现了一个类似的问题,它处理的是一个空值,所以没关系。