[英]Getting the actual type from reflection fieldInfo
I'm writing a generic wrapper around a software's GUI API which has the ability to process quite a few of its own 'built-in' types but I can't figure out how to get it what it needs. 我正在围绕软件的GUI API编写一个通用包装器,该包装器能够处理许多自己的“内置”类型,但我不知道如何获得所需的内容。 For example, I'm doing this to handle strings:
例如,我这样做是为了处理字符串:
("MakeTextField" and "MakeField" are pseudo-code, which take a value, display a GUI element and then return the value from the GUI for storage) (“ MakeTextField”和“ MakeField”是伪代码,它们采用一个值,显示一个GUI元素,然后从GUI返回该值以进行存储)
public static void FieldInfoMakeField<T>(T instance, System.Reflection.FieldInfo fieldInfo)
{
string label = fieldInfo.Name;
if (fieldInfo.FieldType == typeof(string))
{
var val = (string)fieldInfo.GetValue(instance);
val = MakeTextField(label, val);
fieldInfo.SetValue(instance, val);
return;
}
//else if ... more types
This is what I have for the API's type where A and B are derrived from a common type, which I can also test for, but I need the derrived type: 这是我对于API的类型所拥有的,其中A和B是从通用类型派生的,我也可以对其进行测试,但是我需要派生类型:
...
else if (fieldInfo.FieldType == typeof(APITypeA))
{
var val = (APITypeA)fieldInfo.GetValue(instance);
val = MakeField<APITypeA>(label, val); // My version, casts internally
fieldInfo.SetValue(APITypeA, val);
return;
}
else if (fieldInfo.FieldType == typeof(APITypeB))
{
var val = (APITypeB)fieldInfo.GetValue(instance);
val = MakeField<APITypeB>(label, val); // My version, casts internally
fieldInfo.SetValue(APITypeB, val);
return;
}
...
This all works, but I have about 10 more copy&paste code blocks for other "APITypes". 所有这些都可以,但是我还有大约10个用于其他“ APIType”的复制和粘贴代码块。 If I wasn't doing this generically, I would just pass in any type derived from the API's base type and it would work, but I can't figure out how to get the fieldInfo's actual type.
如果我不是一般性地执行此操作,则只需传入从API基本类型派生的任何类型,它就可以工作,但我不知道如何获取fieldInfo的实际类型。 If I print it, it will print the name of the derived types, but I can't seem to get them out.
如果我打印它,它将打印派生类型的名称,但是我似乎无法将它们弄清楚。
I hope I'm stating my problem well enough. 我希望我能很好地说明我的问题。 This is highly situational but seems like it should be possible.
这是高度情况,但似乎应该可行。 If I could just get the type that FieldType() prints, I would be gold.
如果我能得到FieldType()打印的类型,那我将是黄金。 Otherwise I have #regions full of else if statements, which certainly isn't as generic as I would like!
否则,我将在#region中充满其他if语句,这肯定不是我想要的通用!
Are you able to provide the Type
of the field to the FieldInfoMakeField
function? 您是否可以将字段的
Type
提供给FieldInfoMakeField
函数?
public static void FieldInfoMakeField<T, V>(T instance, FieldInfo fieldInfo)
{
string label = fieldInfo.Name;
var val = (V)fieldInfo.GetValue(instance);
val = MakeField<V>(label, val);
fieldInfo.SetValue(instance, val);
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.