如何解决使用反射我们如何判断类属性是否为可为空的集合并获取其数据类型?
我对不可为空集合的属性没有任何问题,但是当该属性是可空集合时,一切都会改变...
给定一个具有可为空集合属性的类(int?[],long?[],List
public class SomeClass
{
public int?[] PropertyX { get; set; }
public long?[] PropertyY { get; set; }
public float?[] PropertyZ { get; set; }
public List<decimal?> PropertyList { get; set; }
public string Name { get; set; }
}
如何判断属性是否为可空集合?
可空集合是否具有任何实际值?
最后什么是可为空的集合数据类型?
public class SomeOtherClass
{
public string Discover(SomeClass someClass)
{
var sb = new StringBuilder();
foreach (var propertyInfo in someClass.GetType().GetProperties())
{
var propValue = propertyInfo.GetValue(someClass,new object[] { });
if (propValue.IsNullableCollection() && propValue.HasValue())
{
sb.AppendFormat("{0} data type is {1}",propValue.GetDataType());
}
}
return sb.ToString();
}
}
示例:
void Main
{
var sc = new SomeClass()
{
PropertyX = new int?[2]{50,10}
};
var output = new SomeOtherClass().Discover(sc);
//Display Output ...
}
“PropertyX 有值,数据类型为 int。”
解决方法
我编写了一个方法,它应该为您提供完成任务所需的所有工具:
public static void Discover(Type mainType)
{
foreach (var pi in mainType.GetProperties())
{
var t = pi.PropertyType;
if (t.IsArray)
{
(var isNullable,var innerT) = ExamineForNullable(t.GetElementType());
Console.WriteLine($"{pi.Name} data type is an array of {innerT} (nullable: {isNullable})");
}
else if (t.GetInterface(nameof(ICollection)) != null)
{
//TODO this is true for dictionaries too!
if (t.IsGenericType)
{
(var isNullable,var innerT) = ExamineForNullable(t.GetGenericArguments()[0]);
Console.WriteLine($"{pi.Name} data type is collection of {innerT} (nullable: {isNullable})");
}
else
{
//TODO
}
}
else
{
Console.WriteLine($"{pi.Name} data type is {t}");
}
}
}
static (bool nullable,Type type) ExamineForNullable(Type t)
=> t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)
? (true,Nullable.GetUnderlyingType(t))
: (false,t);
让我们用下面的类来运行它,它是你示例类的修改版本:
public class SomeClass
{
public int?[] PropertyX { get; set; }
public List<decimal?> List1 { get; set; }
public List<decimal> List2 { get; set; }
public string Name { get; set; }
public Dictionary<string,decimal?> Dictionary { get; set; }
}
(...)
Discover(typeof(SomeClass));
请注意,您不需要类的对象来检查类型:Discover( new SomeClass())
与 Discover(typeof(SomeClass)
。
输出为:
PropertyX data type is an array of System.Int32 (nullable: True)
List1 data type is collection of System.Decimal (nullable: True)
List2 data type is collection of System.Decimal (nullable: False)
Name data type is System.String
Dictionary data type is collection of System.String (nullable: False)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。