[英]Generic and Overloads with .NET Compact Framework
Please see the edit below, I've made the question much simpler! 请查看下面的编辑,我使问题变得更加简单!
I would like to create my own serialization method. 我想创建自己的序列化方法。
I have a generic reference I'd like to serialize. 我有一个要序列化的通用参考。 This generic reference has a chance of just being a typical value type (single, int16 etc).
此泛型引用有可能只是典型的值类型(单值,int16等)。 In that case, I would like to just call the appropriate overloaded method:
BitConverter.GetBytes( genericRefThatIsACommonValueType )
without resorting to type checking (for single
or int16
and etc). 在那种情况下,我只想调用适当的重载方法:
BitConverter.GetBytes( genericRefThatIsACommonValueType )
而不必求助于类型检查(对于single
或int16
等)。
First off, I'd like to know if what I'm asking is possible (because it would look and feel a lot nicer). 首先,我想知道我要问的问题是否可能(因为它看起来和感觉要好得多)。 And secondly, do you think there is a better way of tackling this type of problem?
其次,您是否认为有更好的方法来解决此类问题? Thanks.
谢谢。
========= EDIT ========== =========编辑==========
Why does the method bar() not compile, when I've checked that data has a type that BitConverter.GetBytes(..) should support in it's overloads. 为什么在我检查数据具有BitConverter.GetBytes(..)在重载中应支持的类型时,方法bar()为什么不编译。 Can I get something similar to this working?
我可以得到类似的东西吗?
public class foo<T>
{
T data;
public foo(T arg)
{
data = arg;
}
public void bar()
{
if(data.GetType() == typeof(int) || data.GetType()== typeof(float))
{
BitConverter.GetBytes(data);
}
}
}
The problem with the bar()
method is that you know it's a type supported by BitConverter.GetBytes()
, but data
is still of type T with no constraints. bar()
方法的问题在于您知道它是BitConverter.GetBytes()
支持的类型,但是data
仍然是T类型,没有任何约束。 It would work if there was a BitConverter.GetBytes<T>()
method. 如果有
BitConverter.GetBytes<T>()
方法,它将起作用。
I'm afraid you'll have to cover each overload manually: 恐怕您必须手动解决每个重载问题:
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Int32:
BitConverter.GetBytes((Int32)data);
break;
case TypeCode.Int64:
BitConverter.GetBytes((Int64)data);
break;
...
}
You could use reflection to determine if it is a primitive type: 您可以使用反射来确定它是否是原始类型:
https://msdn.microsoft.com/en-us/library/system.type.isprimitive(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.type.isprimitive(v=vs.110).aspx
Keep in mind that string is not a value type, so if you'd like to handle that, you'll want to check whether it is a string. 请记住,字符串不是值类型,因此,如果要处理该值,则需要检查它是否为字符串。 but, at least at that point it's a lot less checking.
但是,至少到那时,检查要少得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.