简体   繁体   English

使用 python.net 获取 C# 枚举描述?

[英]Get C# enum descriptions with python.net?

I'm using python.NET with a C# API.我正在使用带有 C# API 的 python.NET。 The dlls load ok, and I can find the enum I need, but can't figure out the right syntax for accessing it's values, names, and descriptions. dll 加载正常,我可以找到我需要的枚举,但无法找出访问它的值、名称和描述的正确语法。

I'm not too familiar with C#, but think the enum is something like我对 C# 不太熟悉,但认为枚举类似于

public enum Things 
{
    X1,
    X2,
    X3,
    X4
}

and I'm trying to do the equivalent of eg我正在尝试做相当于例如

var values = Enum.GetValues(typeof(Things));

although I also want to access the names and descriptions.虽然我也想访问名称和描述。 There's a 'GetNames' method, and an 'Overloads' method which I think might be what's required for those.有一个“GetNames”方法和一个“Overloads”方法,我认为这可能是这些方法所需要的。

I'm stuck on the syntax required to use unbound methods in python.Net.我被困在 python.Net 中使用未绑定方法所需的语法上。

In[1]: Things.GetNames
Out[1]: <unbound method 'GetNames'>

I can get individual values我可以获得个人价值

In[2]: Things.X1
Out[2]: 21

but I would really like to understand the proper way to get this information--and the descriptions, which I can't currently find--using Python.NET.但我真的很想了解使用 Python.NET 获取这些信息的正确方法——以及我目前无法找到的描述。


ETA1: Figured out part of what I am doing wrong. ETA1:找出我做错的一部分。 Can get values and names as follows:可以按如下方式获取值和名称:

from System import Enum
values = Enum.GetValues(Things)
names = Enum.GetNames(Things)

The above return System.String[] but I can iterate over them in a list comprehesion to get lists of names and values.上面的返回 System.String[] 但我可以在列表综合中迭代它们以获得名称和值的列表。

but still unsure how to get the descriptions.但仍然不确定如何获得描述。 Don't see any obvious methods for this.没有看到任何明显的方法。

In [17]:dir(Enum)
Out[17]: 
['CompareTo',
 'Equals',
 'Finalize',
 'Format',
 'GetHashCode',
 'GetName',
 'GetNames',
 'GetType',
 'GetTypeCode',
 'GetUnderlyingType',
 'GetValues',
 'HasFlag',
 'IsDefined',
 'MemberwiseClone',
 'Overloads',
 'Parse',
 'ReferenceEquals',
 'ToObject',
 'ToString',
 'TryParse',
 '__call__',
 '__class__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__overloads__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']

ETA2: The approach I was using was fine, but the API turned out to be buggy. ETA2:我使用的方法很好,但结果证明 API 有问题。

Try the following:请尝试以下操作:

from System import Enum

Enum.GetName(Things, 21) # returns "X1"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM