C# 使用反射更改属性的类型

C# 使用反射更改属性的类型,c#,.net,reflection,types,properties,C#,.net,Reflection,Types,Properties,让我们假设我有以下类: public class UniqueEntity { public object Key { get; set; } } 我想要的是能够在运行时将密钥的类型从System.Object更改为System.Int32 如果可以的话,我想唯一可以实现的方法就是使用反射 属性的类型可以通过PropertyType的属性PropertyInfo获得。对于冗余,非常抱歉 typeof(UniqueEntity).GetProperty("Key").PropertyTy

让我们假设我有以下类:

public class UniqueEntity {
    public object Key { get; set; }
}
我想要的是能够在运行时将密钥的类型从System.Object更改为System.Int32

如果可以的话,我想唯一可以实现的方法就是使用反射

属性的类型可以通过PropertyType的属性PropertyInfo获得。对于冗余,非常抱歉

typeof(UniqueEntity).GetProperty("Key").PropertyType;
问题是它是只读的。我无法将该值设置为PropertyType=typeofint


是否有可能更改属性的类型?

否。任何类成员的类型,无论是字段、属性还是方法返回值,以及任何方法参数的类型,都是在编译时确定的

在您的示例中,可以在属性中存储Int32。它将被装箱,您可以根据需要将其转换回Int32。但是属性本身的类型仍然是Object。

好的,所以

主要问题是我上了这门课:

public class UniqueEntity {
    [key]
    public object Key { get; set; }
}
但EntityFramework在处理对象键时会弄乱表的创建。我的想法是键可以是任何类型,由子类指定

我开始使用泛型:

public class UniqueEntity<T> where T : IComparable, IComparable<T>
{
     [Key]
     public T Key { get; set; }
}
在这个小类的帮助下,我们可以创建自己的自定义类型,以提供给EntityFramework,并使用一个新属性,该属性现在具有[Key]注释:

    var context = new Modifier("NewKey", 0);
    var uniqueEntityType = context.MapType(typeof(UniqueEntity).GetTypeInfo());
    var keyType = uniqueEntityType.GetProperty("Key").PropertyType;
    var keyAttrs = uniqueEntityType.GetProperty("Key").GetCustomAttributes();
    var newKeyType = uniqueEntityType.GetProperty("NewKey").PropertyType;
    var newKeyAttrs = uniqueEntityType.GetProperty("NewKey").GetCustomAttributes();
    Console.WriteLine("Key Property. Type: {0}, Attribute: {1}", keyType, keyAttrs.FirstOrDefault());
    Console.WriteLine("NewKey Property. Type: {0}, Attribute: {1}", newKeyType, newKeyAttrs.FirstOrDefault());
    Console.ReadLine();

记录在案。我之所以要这样做,是因为键将使用属性进行注释。外部框架将标识该属性并从PropertyType获取其类型。如果返回System.Int32而不是System.ObjectInteresting问题,那就太好了。我不相信你能在运行时做到这一点。但作为一个对象,您可以在其中存储任何内容,然后执行运行时强制转换。这不是您想要的,但您可以继承该类并创建强制转换该属性的新属性,并且只使用该新属性。这样做会实现什么?任何使用该属性的代码都将假定该类型为Object,并且不会调用仅在Int32或算术运算符上工作的方法。这看起来像是XY问题的典型案例:。问题是外部框架使用PropertyType中的值来执行其工作。如果它的System.Object是错误的。@MatiCicero:你不能为这个属性创建不同类型的类吗?您可以使用属性来调整框架的行为吗?框架中是否有钩子允许您进行自定义处理?@MatiCicero:对不起。具体问题不会改变语言的规则。听起来您必须创建一个垫片对象,它可以作为外部框架和内部实体类型之间的代理。
    var context = new Modifier("NewKey", 0);
    var uniqueEntityType = context.MapType(typeof(UniqueEntity).GetTypeInfo());
    var keyType = uniqueEntityType.GetProperty("Key").PropertyType;
    var keyAttrs = uniqueEntityType.GetProperty("Key").GetCustomAttributes();
    var newKeyType = uniqueEntityType.GetProperty("NewKey").PropertyType;
    var newKeyAttrs = uniqueEntityType.GetProperty("NewKey").GetCustomAttributes();
    Console.WriteLine("Key Property. Type: {0}, Attribute: {1}", keyType, keyAttrs.FirstOrDefault());
    Console.WriteLine("NewKey Property. Type: {0}, Attribute: {1}", newKeyType, newKeyAttrs.FirstOrDefault());
    Console.ReadLine();