SetVariable to Enum with Iron Python

SetVariable to Enum with Iron Python

是否可以这样做?

public enum Letter { A, B, C }
// Suppose I have a scope already set up for Iron Python
scope.SetVariable("Letter", Letter)

这当然是错误的,但希望在python中实现这样的目标:

print(Letter.A) => A

我试过了

scope.SetVariable("Letter", DynamicHelpers.GetPythonTypeFromType(typeof(Letter)))

但在 python 我最终不得不这样做:

print(Letter().A)

这似乎是错误的,因为看起来我正在实例化一个 class。有没有办法让 Letter.A 有效?

你一定是做错了什么你没有表现出来,因为它对我来说很好。

var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("Letter", DynamicHelpers.GetPythonTypeFromType(typeof(Letter)));
engine.Execute(@"
from System import Enum
print(Letter.A)
print(Letter.B)
print(Letter.C)
print(Enum.GetNames(Letter))
print(dir(Letter))
", scope);
A
B
C
Array[str](('A', 'B', 'C'))
['A', 'B', 'C', 'CompareTo', 'Equals', 'Format', 'GetHashCode', 'GetName', 'GetNames', 'GetType', 'GetTypeCode', 'GetUnderlyingType', 'GetValues', 'HasFlag', 'IsDefined', 'MemberwiseClone', 'Parse', 'ReferenceEquals', 'ToBoolean', 'ToByte', 'ToChar', 'ToDateTime', 'ToDecimal', 'ToDouble', 'ToInt16', 'ToInt32', 'ToInt64', 'ToObject', 'ToSByte', 'ToSingle', 'ToString', 'ToType', 'ToUInt16', 'ToUInt32', 'ToUInt64', 'TryParse', '__and__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__invert__', '__le__', '__lt__', '__ne__', '__new__', '__nonzero__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__xor__', 'value__']