通过反射获取字符串数组的长度
是否可以通过反射知道字符串数组的长度 - 没有对象实例?
例如在这种情况下: 2.
public string[] Key
{
get { return new string[] { Name, Type }; }
}
编辑:好的,我不会尝试这样做,它没有多大意义。
Is it possible to know the length of a string array - without having an object instance - via reflection?
E.g. in this case: 2.
public string[] Key
{
get { return new string[] { Name, Type }; }
}
EDIT: ok, I will not try to do this, it doesn't make much sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许你的意思是“没有数组的确切类型”。 C# 数组均派生自
Array
,因此您可以将 Array 引用强制转换为Array
并使用Length
属性。如果您确实想要反映该属性,
则从这里您必须使用各种库之一将字节解码为 IL OpCode(例如 https://gist.github.com/104001)。您正在寻找的操作码是
newarr
。newarr
之前最后一次压入的 int32 是数组的大小。Perhaps you mean "without having the exact type of the Array". C# Arrays all derive from
Array
, so you can cast an Array reference toArray
and use theLength
property.If you TRULY wants to reflect the property,
from here you'll have to use one of the various libraries to decode bytes to IL OpCodes (for example https://gist.github.com/104001) . The OpCode you are looking for is
newarr
. The last push of an int32 before thenewarr
is the size of the array.那里发生了两件事……一旦有了数组,告诉数组的长度就非常简单了;您只需调用
.Length
(在向量的情况下)。但是,您提到了一个实例,并且正在显示一个实例属性;这让我认为这是你缺少的包含对象。在这种情况下……不。您无法对空实例进行 virtcall。尝试对类的实例成员使用静态调用是非常邪恶的; IIRC 运行时会因此而踢你。
但是,您只需添加
static
修饰符即可将其设为静态属性。然后,您只需将null
作为实例传递给反射即可。You have two things going on there... telling the length of an array is pretty simple once you have an array; you just call
.Length
(in the case of a vector).However, you mention an instance, and you are showing an instance property; which makes me think it is the containing object you lack. In which case... no. You can't make a virtcall on a null instance. And trying to use static-call on an instance member of a class is very evil; IIRC the runtime will kick you for this.
You could, however, make it a static property just by adding the
static
modifier. Then you just pass innull
as the instance to reflection.我猜你的意思是你想知道该属性被调用时将返回的数组的大小?
我认为你不能明智地做到这一点。
如果该属性有条件,那么它可能返回不同大小的数组,所以
您必须评估该房产才能知道其大小。这可能会产生副作用或依赖于对象(或静态)中的其他值。
考虑这个:-
基本上,您必须运行代码。
I guess you mean you want to know the size of the array the property will return if it were called?
I don't think you can do it sensibly.
If the property had a conditional then it could return different sized arrays, so
you'd have to evaluate the property to know the size. Which could have side effects or be dependent on other values in the object (or statics).
Consider this one:-
Basically, you'd have to run the code.