2

我想编写以下函数,该函数采用一个随机的 Dot Net 类,该类已知具有一个已调用的属性Amount,并返回该属性的 Dot Net 类型的一些指示。 Amount通常是可以为空的类型,因此在创建时instance会以null(Python ) 结尾。None

def learn_type(test_class):

    '''Given Dot Net class test_class, return the type of the nullable Amount property.'''

    instance = test_class()
    answer = type(instance.Amount) # always NoneType

    return answer

获得类型指示的正确方法是instance.Amount什么?

除了上面的代码之外,我还尝试过反省test_class.Amountinstance.Amount. 我能够获得getset_descriptor,但我也无法确定如何从该对象中提取类型指示符。

这是针对某些 ETL 代码的,其目标之一是通知调用程序输入中遇到的错误数据类型。我的代码想知道遇到了什么,以及预期的类型。

4

1 回答 1

2

最好的办法是使用普通的 .NET System.Reflection API:

instance = test_class()
answer = instance.GetType().GetProperty("Amount").PropertyType

起点是System.Type;所有 .NET 类型元数据都可以从那里获得。

于 2013-10-15T19:42:03.837 回答