如何判断 PropertyInfo 是否属于特定枚举类型?

发布于 2024-08-07 08:57:13 字数 1266 浏览 7 评论 0原文

我有以下代码:

public class DataReader<T> where T : class
{
    public T getEntityFromReader(IDataReader reader, IDictionary<string, string> FieldMappings)
    {
        T entity = Activator.CreateInstance<T>();
        Type entityType = entity.GetType();
        PropertyInfo[] pi = entityType.GetProperties();
        string FieldName;

        while (reader.Read())
        {
            for (int t = 0; t < reader.FieldCount; t++)
            {
                foreach (PropertyInfo property in pi)
                {
                    FieldMappings.TryGetValue(property.Name, out FieldName);

                    Type genericType = property.PropertyType;

                    if (!String.IsNullOrEmpty(FieldName))
                        property.SetValue(entity, reader[FieldName], null);
                }
            }
        }

        return entity;
    }
}

当我到达 Enum 类型的字段时,或者在本例中 NameSpace.MyEnum 时,我想做一些特殊的事情。我不能简单地 SetValue 因为来自数据库的值是“m”,而 Enum 中的值是“Mr”。所以我需要调用另一个方法。我知道!遗留系统对吗?

那么如何确定 PropertyInfo 项何时属于特定枚举类型?

因此,在上面的代码中,我想首先检查 PropertyInfo 类型是否属于特定枚举,如果是,则调用我的方法,如果不是,则只需允许 SetValue运行。

I have the following code:

public class DataReader<T> where T : class
{
    public T getEntityFromReader(IDataReader reader, IDictionary<string, string> FieldMappings)
    {
        T entity = Activator.CreateInstance<T>();
        Type entityType = entity.GetType();
        PropertyInfo[] pi = entityType.GetProperties();
        string FieldName;

        while (reader.Read())
        {
            for (int t = 0; t < reader.FieldCount; t++)
            {
                foreach (PropertyInfo property in pi)
                {
                    FieldMappings.TryGetValue(property.Name, out FieldName);

                    Type genericType = property.PropertyType;

                    if (!String.IsNullOrEmpty(FieldName))
                        property.SetValue(entity, reader[FieldName], null);
                }
            }
        }

        return entity;
    }
}

When I get to a field of type Enum, or in this case NameSpace.MyEnum, I want to do something special. I can't simply SetValue because the value coming from the database is let's say "m" and the value in the Enum is "Mr". So I need to call another method. I know! Legacy systems right?

So how do I determine when a PropertyInfo item is of a particular enumeration type?

So in the above code I'd like to first check whether the PropertyInfo type is of a specif enum and if it is then call my method and if not then simply allow SetValue to run.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

新人笑 2024-08-14 08:57:13

这是我成功使用的

property.PropertyType.IsEnum

Here is what I use with success

property.PropertyType.IsEnum
小耗子 2024-08-14 08:57:13
static void DoWork()
{
    var myclass = typeof(MyClass);
    var pi = myclass.GetProperty("Enum");
    var type = pi.PropertyType;

    /* as itowlson points out you could just do ...
        var isMyEnum = type == typeof(MyEnum) 
        ... becasue Enums can not be inherited
    */
    var isMyEnum = type.IsAssignableFrom(typeof(MyEnum)); // true
}
public enum MyEnum { A, B, C, D }
public class MyClass
{
    public MyEnum Enum { get; set; }
}
static void DoWork()
{
    var myclass = typeof(MyClass);
    var pi = myclass.GetProperty("Enum");
    var type = pi.PropertyType;

    /* as itowlson points out you could just do ...
        var isMyEnum = type == typeof(MyEnum) 
        ... becasue Enums can not be inherited
    */
    var isMyEnum = type.IsAssignableFrom(typeof(MyEnum)); // true
}
public enum MyEnum { A, B, C, D }
public class MyClass
{
    public MyEnum Enum { get; set; }
}
南薇 2024-08-14 08:57:13

在上面的代码中,

bool isEnum = typeof(Enum).IsAssignableFrom(typeof(genericType));

将告诉您当前类型是否是(派生自)枚举。

In your above code,

bool isEnum = typeof(Enum).IsAssignableFrom(typeof(genericType));

will get you whether or not the current type is (derived from) an enum or not.

放飞的风筝 2024-08-14 08:57:13

这就是我将数据表转换为强类型列表时的处理方式

/// <summary>
        /// Covert a data table to an entity wiht properties name same as the repective column name
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ConvertDataTable<T>(this DataTable dt)
        {
            List<T> models = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T model = (T)Activator.CreateInstance(typeof(T));
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

                foreach (PropertyDescriptor prop in properties)
                {
                    //get the property information based on the type
                    System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperties().Last(p => p.Name == prop.Name);

                    var ca = propertyInfo.GetCustomAttribute<PropertyDbParameterAttribute>(inherit: false);
                    string PropertyName = string.Empty;
                    if (ca != null && !String.IsNullOrWhiteSpace(ca.name) && dt.Columns.Contains(ca.name))  //Here giving more priority to explicit value
                        PropertyName = ca.name;
                    else if (dt.Columns.Contains(prop.Name))
                        PropertyName = prop.Name;

                    if (!String.IsNullOrWhiteSpace(PropertyName))
                    {
                        //Convert.ChangeType does not handle conversion to nullable types
                        //if the property type is nullable, we need to get the underlying type of the property
                        var targetType = IsNullableType(propertyInfo.PropertyType) ? Nullable.GetUnderlyingType(propertyInfo.PropertyType) : propertyInfo.PropertyType;
                        // var propertyVal = Convert.ChangeType(dr[prop.Name], targetType);
                        //Set the value of the property
                        try
                        {
                            if (propertyInfo.PropertyType.IsEnum)
                                prop.SetValue(model, dr[PropertyName] is DBNull ? (object)null : Enum.Parse(targetType, Convert.ToString(dr[PropertyName])));
                            else
                                prop.SetValue(model, dr[PropertyName] is DBNull ? (object)null : Convert.ChangeType(dr[PropertyName], targetType));
                        }
                        catch (Exception ex)
                        {
                            //Logging.CustomLogging(loggingAreasType: LoggingAreasType.Class, loggingType: LoggingType.Error, className: CurrentClassName, methodName: MethodBase.GetCurrentMethod().Name, stackTrace: "There's some problem in converting model property name: " + PropertyName + ", model property type: " + targetType.ToString() + ", data row value: " + (dr[PropertyName] is DBNull ? string.Empty : Convert.ToString(dr[PropertyName])) + " | " + ex.StackTrace);
                            throw;
                        }
                    }
                }
                models.Add(model);
            }
            return models;
        }

This is how I handle when I convert a data table into a strongly typed list

/// <summary>
        /// Covert a data table to an entity wiht properties name same as the repective column name
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ConvertDataTable<T>(this DataTable dt)
        {
            List<T> models = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T model = (T)Activator.CreateInstance(typeof(T));
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

                foreach (PropertyDescriptor prop in properties)
                {
                    //get the property information based on the type
                    System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperties().Last(p => p.Name == prop.Name);

                    var ca = propertyInfo.GetCustomAttribute<PropertyDbParameterAttribute>(inherit: false);
                    string PropertyName = string.Empty;
                    if (ca != null && !String.IsNullOrWhiteSpace(ca.name) && dt.Columns.Contains(ca.name))  //Here giving more priority to explicit value
                        PropertyName = ca.name;
                    else if (dt.Columns.Contains(prop.Name))
                        PropertyName = prop.Name;

                    if (!String.IsNullOrWhiteSpace(PropertyName))
                    {
                        //Convert.ChangeType does not handle conversion to nullable types
                        //if the property type is nullable, we need to get the underlying type of the property
                        var targetType = IsNullableType(propertyInfo.PropertyType) ? Nullable.GetUnderlyingType(propertyInfo.PropertyType) : propertyInfo.PropertyType;
                        // var propertyVal = Convert.ChangeType(dr[prop.Name], targetType);
                        //Set the value of the property
                        try
                        {
                            if (propertyInfo.PropertyType.IsEnum)
                                prop.SetValue(model, dr[PropertyName] is DBNull ? (object)null : Enum.Parse(targetType, Convert.ToString(dr[PropertyName])));
                            else
                                prop.SetValue(model, dr[PropertyName] is DBNull ? (object)null : Convert.ChangeType(dr[PropertyName], targetType));
                        }
                        catch (Exception ex)
                        {
                            //Logging.CustomLogging(loggingAreasType: LoggingAreasType.Class, loggingType: LoggingType.Error, className: CurrentClassName, methodName: MethodBase.GetCurrentMethod().Name, stackTrace: "There's some problem in converting model property name: " + PropertyName + ", model property type: " + targetType.ToString() + ", data row value: " + (dr[PropertyName] is DBNull ? string.Empty : Convert.ToString(dr[PropertyName])) + " | " + ex.StackTrace);
                            throw;
                        }
                    }
                }
                models.Add(model);
            }
            return models;
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文