[英]Casting object instance to actual type
I send several different kinds of package
classes, which I serialize and send over the network. 我发送了几种不同的
package
类,我将它们序列化并通过网络发送。 All packages extend the AbstractPackage
: 所有软件包都扩展了
AbstractPackage
:
public abstract class AbstactPackage() {}
public class UpdatePackage : AbstractPackage {
public float x, y, rot;
public UpdatePackage(float pX, float pY, float pRot) {
x = pX; y = pY; rot = pRot;
}
}
After the package was received at the other computer it gets serialized into an abstractPackage instance and readResponse is called. 在另一台计算机上收到该程序包后,它将被序列化为abstractPackage实例,并调用readResponse。 But now I need to determine which type this instance is exactly (eg UpdatePackage)
但是现在我需要确定该实例的确切类型(例如UpdatePackage)
private void readResponse(AbstractPackage p) {
if(p is UpdatePackage) readResponse(p as UpdatePackage);
}
private void readResponse(UpdatePackage p) { ... }
At the moment I have 30 different if statement in the readResponse function for every kind of package I have. 目前,对于每种包装,在readResponse函数中有30种不同的if语句。 Is there a way I can do this more dynamically?
有没有办法可以更动态地做到这一点?
I cannot use the dynamic keyword because I am working with unity and it uses an old dotNet version. 我无法使用dynamic关键字,因为我正在使用unity,并且它使用的是旧版本的dotNet。
You could use a dictionary from the type to a delegate to call when you receive a package of that type. 当您收到该类型的程序包时,可以使用从类型到委托的字典来调用。 So for example:
因此,例如:
class PackageReader
{
private static readonly Dictionary<Type, Action<AbstractPackage>> responseReaders;
static PackageReader()
{
responseReaders = new Dictionary<Type, Delegate>();
RegisterReader<UpdatePackage>(ReadUpdatePackage);
RegisterReader<DownloadPackage>(ReadDownloadPackage);
...
}
private static void RegisterReader<T>(Action<T> reader)
{
Action<AbstractPackage> d = package => reader((T) package);
responseReaders.Add(typeof(T), d);
}
private static void ReadResponse(AbstractPackage p)
{
responseReaders[p.GetType()].Invoke(p);
}
private static void ReadUpdatePackage(UpdatePackage p) { ... }
private static void ReadDownloadPackage(DownloadPackage p) { ... }
...
}
(I've made each "read" method have a different name so that the method group conversion is clearly unambiguous.) (我使每个“读取”方法都有一个不同的名称,以便方法组转换显然是明确的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.