質問

I need to pass values to a method, along with an indication of whether each value is specified or unspecified, since null is a valid value itself, and therefore cannot be interpreted as "unspecified".

I took the generic approach and created a simple container for such values (see below), but is this the right way to go? Are there better ways to approach this problem - e.g. does a class like this already exist in the framework?

public struct Omissible<T>
{
  public readonly T Value;
  public readonly bool IsSpecified;
  public static readonly Omissible<T> Unspecified;

  public Omissible(T value)
  {
    this.Value = value;
    this.IsSpecified = true;
  }
}

The method signature could look like the following, allowing the caller to indicate that certain values shouldn't be updated (unspecified), others should be set to null/another value (specified).

public void BulkUpdate(int[] itemIds, 
  Omissible<int?> value1, Omissible<string> value2) // etc.
役に立ちましたか?

解決

This is the best one can theoretically do. In order to distinguish a general T from a "T or null" you need one possible state more than a variable of type T can hold.

For example, a 32 bit int can hold 2^32 states. If you want to save a null value in addition you need 2^32 + 1 possible states which does not fit into a 4 byte location.

So you need a bool value in addition. (Theoretically speaking you just need log2(2^32 + 1) - 32 bits for the Omissible<int> case, but an easy way to store this is a bool).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top