我的部分软件正在使用反射。我遇到的问题是虽然我可以获取属性的类型,但我无法使用PropertyInfo中的Type
转换字符串值。这就是我在示例代码中使用t
的原因。使用类型变量转换为Enum
下面的代码演示了错误消息作为代码注释的问题。语法错误在t
上。我该如何解决这个问题?感谢
class Program
{
static void Main(string[] args)
{
Type t = typeof(Letters);
Letters letter = "A".ToEnum<t>(); //-- Type or namespace expected.
}
}
public enum Letters { A, B, C }
//-- This is a copy of the EmunHelper functions from our tools library.
public static class EnumExt
{
public static T ToEnum<T>(this string @string)
{
int tryInt;
if (Int32.TryParse(@string, out tryInt)) return tryInt.ToEnum<T>();
return (T)Enum.Parse(typeof(T), @string);
}
public static T ToEnum<T>(this int @int)
{
return (T)Enum.ToObject(typeof(T), @int);
}
}
解决方案:
因为当值是使用反射设置,枚举的实际类型被接受以下工程。其中myObject.Letter = result
不是。
Type t = currentProperty.PropertyType;
Enum result = Enum.Parse(t, @string) as Enum;
ReflectionHelper.SetProperty(entity, "LetterPropertyName", result);
谢谢大家的帮助。
你试图解决的一般问题是什么?它看起来像你试图转换为编译时不知道的类型。那是对的吗? –
这是正确的!我正在试图将解决方案中给出的答案强硬起来。 –
我注意到两种解决方案都以明确的演员结束。如果你可以这样做''A“.ToEnum();'会很好。话虽如此,我认为这可能是不可能的(不确定C#4中的动态变化是否可能)。如果你能解释为什么你要这样做,那么可能会有更好的方法来解决这个问题。 –