将Type转换为PropertyType

本文关键字:PropertyType 转换 Type | 更新日期: 2023-09-27 18:14:23

我是c#中的反射新手,有类似的东西:

class A
{
    DateTime _time = DateTime.Now;
    public DateTime Time
    {
       set
       {
          _time = value;
       }
       get
       {
          return _time;
       }
    }
}

这个方法在应用程序的某个地方:

public Type GetSomeType(int num)
{
    switch (num)
    {
        case 0:
            DateTime time = DateTime.Now;
            return time.GetType();
        case 1:
            int i = 5;
            return i.GetType();
        default:
            return null;
    }
}

我要做的是用GetSomeType方法的结果设置A类的Time属性:

A MyClass = new A();
MyClass.Time = (DateTime)GetSomeType(0); //Clearly, this does not work

我不知道这是可能的还是我完全错了?在我的实际应用中,它更复杂,因为我正在使用PropertyInfo,但现在我很乐意掌握这个概念。

感谢

Juergen

将Type转换为PropertyType

这当然是行不通的,因为你把类型和类型的值(或实例)混在了一起。

你可能需要研究的是PropertyInfo.GetValue (PropertyInfo.SetValue可能同样相关,这取决于你接下来想做什么,太)-但我认为你可能需要考虑你想做什么;例如,在您的示例中,您可以只返回一个对象,或者可能是动态的,因为您直接实例化并处理该值。但是听起来你想要获得某个东西的现有实例的值。

说如果你有一个A和一个B,你想获得B.a的值并用它设置A.a,从你的解释中不清楚为什么你不能只做B.a = A.a,或者鉴别器num适合什么;但是如果你必须使用反射已经有PropertyInfo,那么:

public dynamic GetSomeValue(object instance, PropertyInfo property)
{
    return property.GetValue(instance, null);
}

虽然,这不是理想的,而且大部分是有缺陷的,如果不是过分的-它将有希望提供足够的信息,使您能够将您可以做的事情与您需要做的事情结合起来。

不需要反射来设置属性Time的类型。它被定义为DateTime的类型。我不确定这是一个反思的问题。

同样在GetSomeType方法中,您不需要实例化对象来检索它们的类型。

public Type GetType(int num)
{
  switch(num)
  {
     case 0:
       return typeof(DateTime);
     case 1:
       return typeof(int)
   }
  return null;
}

首先,而不是这个:

DateTime time = DateTime.Now;
return time.GetType();

你可以这样做:

return typeof(DateTime);

同样,如果你通过PropertyInfo:

设置属性,你也不需要强制类型转换(只是猜测)
propInfo.SetValue(instance, value, null);

,其中变量值可以是对象类型,只有运行时类型必须匹配,您也可以这样检查:

if (value == null || propInfo.PropertyType == value.GetType())  

我还是想知道你在做什么。

Type的含义可能有一些误解。它只表示类型对象,没有其他任何东西。您的代码可以简化为以下内容,其行为将完全相同:

public Type GetSomeType(int num)
{
    switch (num)
    {
        case 0:
            return typeof(DateTime);
        case 1:
            return typeof(int);
        default:
            return null;
    }
}

我猜你想返回object,或者类似的东西:

public object GetSomeType(int num)
{
    switch (num)
    {
        case 0:
            return DateTime.Now;
        case 1:
            return 5;
        default:
            return null;
    }
}

这应该对你有用。但是我不知道你为什么要那样做。

您需要更改实现以使用对象返回类型而不是type作为返回类型,并且您必须使用可空的datetime类型。请查看下面的示例代码:

class A
{
    DateTime? _time = DateTime.Now;
    public DateTime? Time
    {
       set
       {
          _time = value;
       }
       get
       {
          return _time;
       }
    }
}

public object GetSomeType(int num)
{
    switch (num)
    {
        case 0:
            DateTime time = DateTime.Now;
            return time;
        case 1:
            int i = 5;
            return i;
        default:
            return null;
    }
}
A MyClass = new A();
MyClass.Time = this.GetSomeType(0) as DateTime?; //This should now work