c# - 使用反射动态地将属性转换为其实际类型

标签 c# entity-framework reflection

我需要动态地将属性转换为其实际类型。我如何/我可以使用反射来做到这一点?

稍微解释一下我正在处理的真实场景。我正在尝试调用 Entity Framework 属性的“First”扩展方法。要在 Framework 上下文对象上调用的特定属性作为字符串传递给方法(以及要检索的记录的 ID)。所以我需要对象的实际类型才能调用 First 方法。

我不能在对象上使用“Where”方法,因为 lambda 或委托(delegate)方法仍然需要对象的实际类型才能访问属性。

此外,由于该对象是由 Entity Framework 生成的,所以我无法将该类型转换为接口(interface)并对其进行操作。

这是场景代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;

namespace NmSpc
{

    public class ClassA
    {
        public int IntProperty { get; set; }
    }

    public class ClassB
    {
        public ClassA MyProperty { get; set; }
    }

    public class ClassC
    {
        static void Main(string[] args)
        {
            ClassB tester = new ClassB();

            PropertyInfo propInfo = typeof(ClassB).GetProperty("MyProperty");
            //get a type unsafe reference to ClassB`s property
            Object property = propInfo.GetValue(tester, null);

            //get the type safe reference to the property
            ClassA typeSafeProperty = property as ClassA;

            //I need to cast the property to its actual type dynamically. How do I/Can I do this using reflection?
            //I will not know that "property" is of ClassA apart from at runtime
        }
    }
}

最佳答案

public object CastPropertyValue(PropertyInfo property, string value) { 
if (property == null || String.IsNullOrEmpty(value))
    return null;
if (property.PropertyType.IsEnum)
{
    Type enumType = property.PropertyType;
    if (Enum.IsDefined(enumType, value))
        return Enum.Parse(enumType, value);
}
if (property.PropertyType == typeof(bool))
    return value == "1" || value == "true" || value == "on" || value == "checked";
else if (property.PropertyType == typeof(Uri))
    return new Uri(Convert.ToString(value));
else
    return Convert.ChangeType(value, property.PropertyType);  }

关于c# - 使用反射动态地将属性转换为其实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/907882/

相关文章:

c# - PropertyGrid、DefaultValueAttribute、动态对象和枚举

c# - 如果文件已存在且在 C# 中具有相同位置,则始终创建新文件

c# - 我们可以在 'app.config' 文件中声明变量吗?

c# - Linq + foreach循环优化

c# - 如何在 DbContext 中的 SaveChanges 中向关系(连接表)添加自定义处理?

c# - 从具有约束的数据库中随机选择数据

c# - 如果使用 NSubstitute 出现问题,则模拟抛出异常的方法

c# - 在 LINQ-to-Entities 中键入成员支持?

c# - 如何使用反射调用泛型类的静态属性?

java - 有没有一个库可以给我一个类在另一个类中出现的所有实例?