一个变量,多个值?

时间:2018-03-15 21:21:21

标签: c# .net

这可能听起来像个奇怪的问题,我觉得简短的回答是'不'。

但是,基于布尔运算符,变量是否可以采用多个值?例如:

//Current implementation
string Variable1 = "A";
string Variable2 = "B";
string Variable3 = "C";

//Sought after implementation
string Variable = "":
Variable = "A" || Variable = "B" || Variable = "C";

这看起来不太可行,特别是因为布尔运算符不能应用于字符串类型,因为,好吧......它们不是布尔值。

2 个答案:

答案 0 :(得分:5)

  

但是,基于布尔运算符,变量是否可以采用多个值?

当然!让我们实现它。我们将使用ImmutableHashSet<T>中的System.Collections.Immutable类型。

struct MySet<T>
{
    public readonly static MySet<T> Empty = default(MySet<T>);
    private ImmutableHashSet<T> items;
    private MySet(ImmutableHashSet<T> items) => this.items = items;
    public ImmutableHashSet<T> Items => this.items ?? ImmutableHashSet<T>.Empty;
    public MySet<T> Add(T item) => new MySet<T>(this.Items.Add(item));
    public static MySet<T> operator |(T item, MySet<T> items) => items.Add(item);
    public static MySet<T> operator |(MySet<T> items, T item) => items.Add(item);
    public static MySet<T> operator |(MySet<T> x, MySet<T> y) => new MySet<T>(x.Items.Union(y.Items));
    public static MySet<T> operator &(MySet<T> items, T item) => new MySet<T>(items.Items.Contains(item) ? ImmutableHashSet<T>.Empty.Add(item) : ImmutableHashSet<T>.Empty);
    public static MySet<T> operator &(T item, MySet<T> items) => new MySet<T>(items.Items.Contains(item) ? ImmutableHashSet<T>.Empty.Add(item) : ImmutableHashSet<T>.Empty);
    public static MySet<T> operator &(MySet<T> x, MySet<T> y) => new MySet<T>(x.Items.Intersect(y.Items));
}

现在我们可以创建一个包含任意类型的多个值的变量,并遵守|&的定律:

    var items1 = MySet<String>.Empty | "Hello" | "Goodbye" | "Whatever";
    var items2 = MySet<String>.Empty | "Goodbye" | "Hello" | "Blah";
    var items3 = items1 & items2;
    var items4 = items1 | items2;
    Console.WriteLine(String.Join(" ", items3.Items)); // "Hello Goodbye"
    Console.WriteLine(String.Join(" ", items4.Items)); // "Hello Goodbye Whatever Blah"

答案 1 :(得分:4)

使用[Flags]属性定义枚举。

参考:What does the [Flags] Enum Attribute mean in C#?

[Flags]
public enum PossibleValues { A = 1, B = 2, C = 4 }

var foo = PossibleValues.A | PossibleValues.B | PossibleValues.C;