如何在运行时识别泛型类型? [英] How to identify a generic type at runtime?

查看:75
本文介绍了如何在运行时识别泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好!



我的情况如下:

Hello!

I have a scenario as follows:

public class Envelope
{

public string MessageId {get;}

public abstract Stream GetStream() 

}







public class Envelope<T> : Envelope
{
public T Body {get;}
}





我还有另外两个名为MessageBus和MessageSender的类,它们负责管理消息并将消息传输到整个应用程序服务。





I have another 2 classes called MessageBus and MessageSender that is responsible to manage and transmit the message to entire application services.

public class MessageBus
{

public void Send(Envelope message)
{
sender.Dispatch(message);
}

}

public class MessageSender
{

public void Dispatch(Envelope message)
{

// THE PROBLEM IS HERE!!!!!
// HOW DO I IDENTIFY THE TYPE OF BODY? 
// On Envelope (base class) the property Body is missing and i can't get the type 
// to try create instance of change type .. and i need to pass body as parameter to 
// another method
}
}





抱歉我的英文不好,非常感谢你的时间:)



我尝试过的事情:



反思可以起作用,但我试图解决它更优雅的方式。



Sorry for my bad english and thank you very much for your time :)

What I have tried:

Reflection can be work, but i trying to solve it with a more 'elegant' way.

推荐答案

引用:

我需要通过body作为另一个方法的参数

and i need to pass body as parameter to another method

其他方法也需要是通用的;或至少接受与T兼容的类型。否则,泛型类中的封装没有意义。

That other method needs to be generic, too; or at least accept a type compatible with T. Otherwise, the encapsulation in the generic class does not make sense.


您应该将以下函数添加到 Envelope中 class:

You should probably add the following function to your Envelope class:
public abstract Type GetBodyType();





然后在派生类中实现它 Envelope< T> ;



And then implement it in the derived class Envelope<T>:

return typeof(T);





或许您需要重新考虑整个设计...您是否正在尝试转换来自另一种语言的模式?



Or maybe you need to reconsider the whole design... Are you trying to convert a pattern from another language?


这里的泛型有什么好处?这些可能被过度使用,然后你会遇到这样的情况。你能不能只将身体粘贴在非通用的Envelope中作为类型对象?



此外,假设需要某种序列化才能发送这个东西一个消息总线,也许有一个基本接口或者你可以用作Body类型的东西?
What is the benefit of generics here? These can be overused and then you get into situations like this. Can you not just stick the body in the non-generic Envelope as type object?

Moreover, presuming some sort of serialization will be required in order to dispatch this thing on a message bus, perhaps there is a base interface or something you can use as the type of Body?


这篇关于如何在运行时识别泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆