计算泛型结构的大小,其中泛型参数仅限于基本类型

时间:2014-07-31 17:43:38

标签: c# .net generics marshalling sizeof

我见过几个similar posts,但我认为我的情景更具体。请考虑以下结构:

public interface ISample<T>
    where T: struct, IComparable, IFormattable, IConvertible
{
    T Value { get; }
    TimeSpan Time { get; }
}

public struct Sample<T>:
    ISample<T>
    where T: struct, IComparable, IFormattable, IConvertible
{
    private readonly T _Value;
    private readonly TimeSpan _Time;

    public Sample (T value) { this._Value = value; this._Time = TimeSpan.Zero; }
    public Sample (T value, TimeSpan time) { this._Time = time; this._Value = value; }

    public T Value { get { return (this._Value); } }
    public TimeSpan Time { get { return (this._Time); } }

    public static readonly Sample<T> Zero = new Sample<T>();

    static Sample ()
    {
        var type = typeof(T);

        if
        (
            (type != typeof(byte))
            && (type != typeof(sbyte))
            && (type != typeof(short))
            && (type != typeof(ushort))
            && (type != typeof(int))
            && (type != typeof(uint))
            && (type != typeof(long))
            && (type != typeof(ulong))
            && (type != typeof(float))
            && (type != typeof(double))
            && (type != typeof(decimal))
        )
        {
            throw (new ArgumentException("The generic argument [<T>] must be a primitive integral or floating point type."));
        }
    }
}

我需要在运行时计算这个结构的大小。使用泛型有可靠的方法吗?由于类型的数量有限,因此对值进行硬编码是一种选择,但不是优选的。任何提示都将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试使用Marshal.SizeOf(typeof(T))来计算通用类型大小。我不确定你是否可以为结构本身使用if,但是你可以将结果添加到你应该知道的结构大小。有关方法here的更多信息。