1

考虑这种类型,它是否像我能做到的那样不可变?

public struct SomeType
{
    public const int OneValue = 1;

    private static readonly one = new SomeType(one);

    private readonly int value;

    private SomeType(int value)
    {
        this.value = value;
    }

    public static One
    {
        get { return this.one; }
    }

    public static implicit operator int(SomeType source)
    {
        return source.value;
    }

    public void SomeSpecialization()
    {
    }
}

这让我可以做到这一点,

var one = SomeType.One;

switch (one)
{
    case SomeType.OneValue:
        ...
}

但是,无论如何我可以删除

public static implicit operator int(SomeType source)
    {
        return source.value;
    }

从类型定义中并使用这样的类型?

var one = SomeType.One;

switch (one)
{
    case SomeType.One:
        ...
}
4

3 回答 3

2

语句中的case表达式switch只能是某些内置类型和enums 的编译时常量。所以答案是否定的:无论你用你的SomeType(没有把它变成一个enum)做什么,你都不能使用SomeType对象作为case表达式。

于 2012-10-01T11:21:08.510 回答
1

如果您不使用Enum,请尝试静态类:

public static class SomeType
{
    public const int OneValue = 1;
    public const int SecondValue = 2;
}
于 2012-10-01T11:29:23.630 回答
0

这有帮助吗?

public struct SomeType<T> where T : IConvertible
{
    private static readonly T _one = (T)Convert.ChangeType(1, typeof(T));
    public static T One { get { return _one; } }
}
于 2012-10-01T11:23:20.347 回答