我想在不使用.NET语言内置支持的情况下输入值.
也就是说,给定一个枚举值,我想要一个表示该值及其类型的引用类型对象.
这是一个能够从后期绑定纯C++代码传递枚举值的子目标,这是一个可能的解决方案,因此,我不是在寻找如何使用例如C#boxing(这很容易,并且在很多方面都无关紧要).
以下代码产生......
c:\projects\test\csharp\hello\main.cs(6,26): error CS0122: 'System.Reflection.RuntimeFieldInfo' is inaccessible due to its protection level
但是,使用更多文档化的FieldInfo类,这是签名所MakeTypedReference要求的,我得到一个例外,说参数不是RuntimeFieldInfo.
不成功的代码,实验,C#:
using System.Windows.Forms;
using Type = System.Type;
using TypedReference = System.TypedReference;
using MethodInfo = System.Reflection.MethodInfo;
using FieldInfo = System.Reflection.FieldInfo;
using RuntimeFieldInfo = System.Reflection.RuntimeFieldInfo;
namespace hello
{
class Startup
{
static void Main( string[] args )
{
Type stringType = typeof( string );
Type messageBoxType = typeof( MessageBox );
Type mbButtonsType = typeof( MessageBoxButtons );
Type mbIconType = typeof( MessageBoxIcon );
Type[] argTypes = { stringType, stringType, mbButtonsType };// }, mbIconType };
MethodInfo showMethod = messageBoxType.GetMethod( "Show", argTypes );
// object mbOkBtn = (object) (MessageBoxButtons) (0);
TypedReference tr = TypedReference.MakeTypedReference(
mbButtonsType,
new RuntimeFieldInfo[]{ mbIconType.GetField( "OK" ) }
);
object mbOkBtn = TypedReference.ToObject( tr );
object[] mbArgs = { "Hello, world!", "Reflect-app:", mbOkBtn };
showMethod.Invoke( null, mbArgs );
}
}
}
Run Code Online (Sandbox Code Playgroud)
一个有助于使上述代码"正常"的答案将是非常好的.
一个答案指出了实现拳击的另一种方式(也许上面完全和完全错误? - 它只是实验性的)也将是非常好的!:-)
编辑:澄清:基本上我跟C#(object)v产量一样.我已经尝试了enum ToObject方法,但不幸的是,虽然这可能在.NET中正常工作,但在C++方面我只是得到了32位整数值.C++方面的问题是传递一个整数作为第三个例如MessageBox.Show只是失败,可能是因为.NET端的默认绑定器没有将它转换为枚举类型,所以我怀疑需要一个合适类型的引用对象实际的论点.
我不确定你想要什么样的拳击,但如果你想要一个TypedReference,只需__makeref()在C#中使用.这是您的程序的工作版本:
using System.Windows.Forms;
using System;
using MethodInfo = System.Reflection.MethodInfo;
namespace hello
{
class Startup
{
static void Main(string[] args)
{
Type stringType = typeof(string);
Type messageBoxType = typeof(MessageBox);
Type mbButtonsType = typeof(MessageBoxButtons);
Type[] argTypes = { stringType, stringType, mbButtonsType };
MethodInfo showMethod = messageBoxType.GetMethod("Show", argTypes);
var OkBtn = MessageBoxButtons.OK;
TypedReference tr = __makeref(OkBtn);
object mbOkBtn = TypedReference.ToObject(tr);
object[] mbArgs = { "Hello, world!", "Reflect-app:", mbOkBtn };
showMethod.Invoke(null, mbArgs);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
890 次 |
| 最近记录: |