TokugawaTakeshi / CrossPlatformOrganizerAppplication

0 stars 0 forks source link

ジェネリック関数に於ける明示的にnullを返す #22

Closed TokugawaTakeshi closed 1 year ago

TokugawaTakeshi commented 1 year ago

@gummoni

DecideOptionalValueメソッドからnullを返したい場合がありますが、C#は

Cannot convert expression type 'null' to return type 'TValueType'

と怒ります。

using Utils;

namespace MockDataSource.Utils;

public abstract class DataMocking
{

  public enum NullablePropertiesDecisionStrategies
  {
    mustGenerateAll,
    mustGenerateWith50PercentageProbability,
    mustSkipIfHasNotBeenPreDefined
  }

  public struct NullablePropertiesDecisionOptions<TPropertyType>
  {
    public NullablePropertiesDecisionStrategies Strategy { get; init; }
    public Func<TPropertyType> RandomValueGenerator { get; init; }
    public TPropertyType? PreDefinedValue { get; init; }
  }

  public static TValueType? DecideOptionalValue<TValueType>(NullablePropertiesDecisionOptions<TValueType> options)
  {

    switch (options.Strategy)
    {

      case NullablePropertiesDecisionStrategies.mustGenerateAll:

        return options.PreDefinedValue ?? options.RandomValueGenerator();

      case NullablePropertiesDecisionStrategies.mustSkipIfHasNotBeenPreDefined:

        return options.PreDefinedValue;

      default:

        return RandomValuesGenerator.GetRandomBoolean() ? options.RandomValueGenerator() : null;

    }

  }

}

どうすれば良いでしょう?

TokugawaTakeshi commented 1 year ago

此方は自分で解決できましたから、閉じさせてもらいます。