如何获取 Nullable Enum 的 toString 方法来构建表达式调用
enum StrategyType
{
Straddle,
Butterfly
}
class Test
{
public StrategyType strategy {get; set;}
}
bool IsNullableEnum(Type t)
{
Type u = Nullable.GetUnderlyingType(t);
return (u != null) && u.IsEnum;
}
var toStringMethod = typeof(Enum).GetMethod("ToString", new Type[] { });
var entity = new Test();
var entityParameter = Expression.Parameter(entity);
Expression memberProperty = Expression.Property(entityParameter, "strategy");
memberProperty = Expression.Call(memberProperty, toStringMethod);
如果我将 Test 类中的 StrategyType Enum 更改为 Nullable,如下所示:
StrategyType? strategyType {get; set;}
然后,我无法找到获取 Nullable Enum 的 toString 方法的方法,类似于我为简单 Enum StrategyType 所做的方法。
任何人都可以帮忙吗?
enum StrategyType
{
Straddle,
Butterfly
}
class Test
{
public StrategyType strategy {get; set;}
}
bool IsNullableEnum(Type t)
{
Type u = Nullable.GetUnderlyingType(t);
return (u != null) && u.IsEnum;
}
var toStringMethod = typeof(Enum).GetMethod("ToString", new Type[] { });
var entity = new Test();
var entityParameter = Expression.Parameter(entity);
Expression memberProperty = Expression.Property(entityParameter, "strategy");
memberProperty = Expression.Call(memberProperty, toStringMethod);
If I change the StrategyType Enum in the Test class to Nullable like below:
StrategyType? strategyType {get; set;}
Then, I am unable to find out the way to get the toString method for Nullable Enum, similar to the one I have done for simple Enum StrategyType.
Can anyone please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,您应该发出对实际类型方法的调用,而不是
Enum
。它适用于可空和不可空值类型,包括枚举。您可以通过使用
GetMethod
调用中的实际类型,或(最好)使用string methodName
的Expressing.Call
重载来实现此目的,例如In general you should emit call to the actual type method, not
Enum
. It would work for both nullable and non nullable value types, includingenum
s.You can do that by using the actual type in
GetMethod
call, or (preferable) theExpressing.Call
overload withstring methodName
, e.g.Nullable<>
有点棘手。当您找到这样的属性时,您必须对照给定实体检查从prop.GetValue(entity)
返回的内容。要么是null
(并且尝试调用ToString()
是不可能的),要么返回值类型(但装箱为对象),但您可以调用正常ToString()
方法。Nullable<>
is a little tricky. When you find such a property you have to check against the given entity what you get back fromprop.GetValue(entity)
. Either this isnull
(and trying to callToString()
would be impossible) or you get back the value type (but boxed as an object), but you can call the normalToString()
method.