我有一个具有枚举类型,整数,字符串等的模型类。
例如;
public class CustomerModel
{
public int id { get; set; }
public CustomerType CustomerType { get; set; }
public DateTime MembershipStartDate { get; set; }
public CustomerClass CustomerClass { get; set; }
public string Surname { get; set; }
public EducationStatus EducationStatus { get; set; }
public Gender Gender { get; set; }
public int NationalityId { get; set; }
}
我需要从该模型类中捕获枚举类型及其名称。我尝试了GetType,GetTypes,GetProperty等,但找不到任何解决方案。如果我可以捕获该枚举类型,则可以在应用程序中的任何地方轻松使用该类型。否则,我需要一个人抓住。请帮助。
答案 0 :(得分:1)
您可以这样做:
private void createUserGuideInTempFolder()
throws IOException {
String inputFileName = "N:\\TestData\\user-guide.pdf";
String baseName = FilenameUtils.getBaseName(inputFileName);
String extension = FilenameUtils.getExtension(inputFileName);
Path tempFilePath = Files.createTempFile(baseName, extension);
Path inputFilePath = Paths.get(inputFileName);
InputStream inStream = Files.newInputStream(inputFilePath);
byte [] fileBytes = IOUtils.toByteArray(inStream);
tempFilePath = Files.write(tempFilePath, fileBytes);
System.out.println(inputFilePath);
// Prints input file: N:\TestData\user-guide.pdf
System.out.println(tempFilePath);
// Prints temp file: N:\apache-tomcat-7.0.65\temp\user-guide3642635958536288074pdf
Path newTempFilePath = Paths.get(tempFilePath.getParent().toString(),
inputFilePath.getFileName().toString());
newTempFilePath = Files.move(tempFilePath, newTempFilePath);
System.out.println(newTempFilePath);
// Prints result file in temp: N:\apache-tomcat-7.0.65\temp\user-guide.pdf
}
这非常简单:获取类的Type type = typeof(YourClass);
var properties = type.GetProperties();
var propertiesWithEnumTypes = properties.Where(x => x.PropertyType.IsEnum);
var typeNames = propertiesWithEnumTypes.Select(x => x.PropertyType.Name);
实例,获取其属性,过滤属性列表以仅保留那些属性类型为enum的属性,将过滤后的列表映射到类型的名称。
如果要获取属性的名称而不是枚举类型的名称,请用Type
替换x.PropertyType.Name
;