我想通过函数名称来调用函数属性(也可以键入)。
在python中,是这样的:
<a href="https://github.com/yanglr">
<img style="position: absolute; top: 76px; right: 0; border: 0" alt="Fork me on GitHub"
src="https://cdn.jsdelivr.net/gh/yanglr/Beautify-cnblogs/images/github-pendant-rightCorner.svg?sanitize=true"></a>
但是C#和类型呢?
我想在转换后的import time
method_to_call = getattr(time, 'clock') # time.clock()
result = method_to_call()
print(result)
上使用sizeof
。在C#中甚至可能吗?
ITEM_STRING_TO_TYPE
答案 0 :(得分:3)
如果用ITEM_STRING_TO_TYPE
来表示Type
,则这里存在一些问题:
int
,long
等不是.NET名称-它们是C#别名(并且.NET针对多种语言);这意味着您需要在别名和Type
(此处的.NET名称分别为System.Int32
和System.Int64
之间)之间特定于语言的映射sizeof
不能与Type
一起使用;有Unsafe.SizeOf<T>()
,但也不能直接与Type
一起使用-它需要泛型,因此您需要通过MakeGenericMethod
List<(string name, int size)> mainList = new List<(string,int)>(new []
{
("bool", sizeof(bool)),
// ...
("ushort", sizeof(ushort)),
});
然后您可以使用:
foreach (var item in mainList)
{
Console.WriteLine("Size of {0} : {1}", item.name, item.size);
}
或:
foreach ((var name, var size) in mainList)
{
Console.WriteLine("Size of {0} : {1}", name, size);
}