简体   繁体   English

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

[英]Calculating the size of a generic struct where generic parameters are restricted to primitive types

I've seen a couple of similar posts but think that my scenario is more specific. 我看过几篇类似的文章,但认为我的情况更具体。 Consider the following struct: 考虑以下结构:

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."));
        }
    }
}

I need to calculate the size of this struct at runtime. 我需要在运行时计算此结构的大小。 Is there a reliable way to do this with generics? 有使用泛型的可靠方法吗? Since the number of types are limited, hard-coding the values is an option but not preferable. 由于类型的数量有限,因此对值进行硬编码是一种选择,但不是可取的。 Any hints would be appreciated. 任何提示将不胜感激。

Try Marshal.SizeOf(typeof(T)) for calculating generic type size. 尝试使用Marshal.SizeOf(typeof(T))来计算通用类型的大小。 I'm not sure if you can use if for the struct itself, but you can add the result to the struct size that you supposed to know. 我不确定是否可以对结构本身使用if,但是可以将结果添加到您应该知道的结构大小中。 More info on the method here . 有关此方法的更多信息,请参见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM