动态设置泛型
我对泛型有疑问,并认为这可能是不可能的,但我想我会把它扔在那里,希望找到某种解决方案。 我有一个使用泛型的对象,我想动态设置泛型。我的问题是,或者反射只能让我到目前为止的原因是,对象需要作为输出参数发送到方法中。有什么建议吗?代码如下
GetConfigurationSettingMessageResponse<DYNAMICALLYSETTHIS> ch;
if (MessagingClient.SendSingleMessage(request, out ch))
{
if (ch.ConfigurationData != null)
{
data = ch.ConfigurationData;
}
}
I have a question with generics, and think this may be impossible but thought Id throw it out there in hopes of finding some sort of solution.
I have an object that uses generics, I want to set the generic on the fly. My problem is, or the reason why reflection can only get me so far, is that the object needs to be sent into a method as an out param. Any suggestions? The code is below
GetConfigurationSettingMessageResponse<DYNAMICALLYSETTHIS> ch;
if (MessagingClient.SendSingleMessage(request, out ch))
{
if (ch.ConfigurationData != null)
{
data = ch.ConfigurationData;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如何制作一个通用的便捷方法,然后使用 反射称之为。
How about make a generic convenience method and then use reflection to call it.
更多的是一种解决方法,而不是直接答案,但是您是否必须编写如此强类型的代码?也许您将其保留为
GetConfigurationSettingMessageResponse
...
More of a workaround than a direct answer, but do you have to write the code so strongly typed? Perhaps you leave it as an
GetConfigurationSettingMessageResponse<object>
and test at a later stage to see what it is:...
编辑:本质上,您需要传递对编译时不知道的类型的引用。在这种情况下,我们需要通过反射来击败编译时检查。
完成此操作后,您可以创建一个辅助方法来让您操作 ch 对象而不是 GetProperty 部分。
EDITED: Essentially, you need to pass in a reference to a type you can't know at compile time. In which case we need to defeat the compile time checking with reflection.
Once you've done this, you could create a helper method to let you maniupulate the ch object instead of the GetProperty part.