質問

誰でもできるので教えていうとジェネリック医薬品を制限する汎用型の引数 T のみ:

  • Int16
  • Int32
  • Int64
  • UInt16
  • UInt32
  • UInt64

私が認識し、 where キーワードが可能なためのインターフェース のみ これらの種類

のようなもの:

static bool IntegerFunction<T>(T value) where T : INumeric 
役に立ちましたか?

解決

C#のいはこれをサポートしていません。Hejlsberg記の理由を実施していないの特徴 インタビューとブルース-Eckel:

これらのゲームを置くことが明らかに複雑である小さな利回りで取得します。ればと思います。が直接サポートされていないの拘束システムに行うことができるので、工場パターンです。きり Matrix<T>, 例えば、 Matrix いを定義するドットの製品。もちろんのことを実現する、最終的に理解する必要の方法を掛ける二つの Tができないとは言いる拘束条件として、少なくともしない場合 Tint, double, や float.でも何ができるようになって違いますので、ご Matrix 取引数として、 Calculator<T>, おり、 Calculator<T>, ていることにな multiply.く実施するまでの Matrix.

しかし、これに巻き込みコードのユーザー自身で Calculator<T> 実施のための各 T 作りたいという話があった。どん伸ばせる、すなわちまた支援を固定した数の種類など intdouble, きら比較的シンプルなインターフェース:

var mat = new Matrix<int>(w, h);

(最小限の実装では、GitHub Gist.)

しかし、また、ユーザに提供することができ、カスタムの種類、必要なものを切り開この実装では、ユーザーに供給でき、自 Calculator う場合がございます。例えば、インスタンスを生成するマトリクスを使用したカスタム桁の浮動小数点実施 DFP, しか書くこのコード:

var mat = new Matrix<DFP>(DfpCalculator.Instance, w, h);

...実施すべての会員 DfpCalculator : ICalculator<DFP>.

代替、残念ながら、制約の中で、仕事の政策授業 またセルゲイShandarの回答.

他のヒント

を考慮した人気の質問は、利息その機能に驚いていいのではない応答に関T4ます。

このサンプルコードをシンプルなどのように利用できる強力なエンジンの洗いかにコンパイラのほとんどは舞台裏とジェネリック医薬品.

を通じてではなく、競とを犠牲にコンパイル時の確実性をできるだけの機能のすべての型のように使い分けられてし(コンパイル時に!).

そのために:

  • 新規作成し テキストテンプレート ファイルと呼ばれ GenericNumberMethodTemplate.tt.
  • 除去の自動生成コード付けすることができます。ものでもない)を行います。
  • 以下のように追加のスニペット:
<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>

<# Type[] types = new[] {
    typeof(Int16), typeof(Int32), typeof(Int64),
    typeof(UInt16), typeof(UInt32), typeof(UInt64)
    };
#>

using System;
public static class MaxMath {
    <# foreach (var type in types) { 
    #>
        public static <#= type.Name #> Max (<#= type.Name #> val1, <#= type.Name #> val2) {
            return val1 > val2 ? val1 : val2;
        }
    <#
    } #>
}

それだけです。います。

保存ファイルは自動的にコンパイルではこのソースファイル:

using System;
public static class MaxMath {
    public static Int16 Max (Int16 val1, Int16 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static Int32 Max (Int32 val1, Int32 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static Int64 Max (Int64 val1, Int64 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt16 Max (UInt16 val1, UInt16 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt32 Max (UInt32 val1, UInt32 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt64 Max (UInt64 val1, UInt64 val2) {
        return val1 > val2 ? val1 : val2;
    }
}

main 方法を確認することができますコンパイル時の確実性:

namespace TTTTTest
{
    class Program
    {
        static void Main(string[] args)
        {
            long val1 = 5L;
            long val2 = 10L;
            Console.WriteLine(MaxMath.Max(val1, val2));
            Console.Read();
        }
    }
}

enter image description here

まだ先の備考:いいえ、この違反に乾燥します。の乾燥の原則はあるのから重複コードに複数の場所が不適切と判断するに難しくなっているためではないかナンス性の向上にも寄与します。

この場合はこちら:したい場合は、変更したときに変えるだけのテンプレート(シングルソースのすべての世代!) で行われます。

をご利用いただくためには、およびユーザーインターフェイス定義を追加-名前空間を宣言してくださいを同一としての一つけることができます自動的に実施)を生成したコードおよびマークをクラスとして partial.その後、これらの追加ラインをテンプレートファイルでの最終編集:

<#@ import namespace="TheNameSpaceYouWillUse" #>
<#@ assembly name="$(TargetPath)" #>

うに正直であること:これは格好いい。

免責事項:このサンプルが大きく影響を受け Metaprogrammingます。純るKevin Hazzardスとボックの砲台があり、船員配乗刊行物.

ある制約のためです。この現実の問題から好みや希望、予算に合用ジェネリック医薬品のための数値計算.

いて更なるといえる必要がありま

static bool GenericFunction<T>(T value) 
    where T : operators( +, -, /, * )

static bool GenericFunction<T>(T value) 
    where T : Add, Subtract

残念ながらみタベースのポリシー-ガイドラインのキーワード struct (価値型) class (参考) new() (デフォルトのコンストラクタ)

またラップのように INullable<T> のように ここではcodeproject.


を適用できる制限での実行時(背の事業者又は検査のために種類もなくの利点を有する一般的なものでした。

回避策を策

interface INumericPolicy<T>
{
    T Zero();
    T Add(T a, T b);
    // add more functions here, such as multiplication etc.
}

struct NumericPolicies:
    INumericPolicy<int>,
    INumericPolicy<long>
    // add more INumericPolicy<> for different numeric types.
{
    int INumericPolicy<int>.Zero() { return 0; }
    long INumericPolicy<long>.Zero() { return 0; }
    int INumericPolicy<int>.Add(int a, int b) { return a + b; }
    long INumericPolicy<long>.Add(long a, long b) { return a + b; }
    // implement all functions from INumericPolicy<> interfaces.

    public static NumericPolicies Instance = new NumericPolicies();
}

アルゴリズム

static class Algorithms
{
    public static T Sum<P, T>(this P p, params T[] a)
        where P: INumericPolicy<T>
    {
        var r = p.Zero();
        foreach(var i in a)
        {
            r = p.Add(r, i);
        }
        return r;
    }

}

使用量:

int i = NumericPolicies.Instance.Sum(1, 2, 3, 4, 5);
long l = NumericPolicies.Instance.Sum(1L, 2, 3, 4, 5);
NumericPolicies.Instance.Sum("www", "") // compile-time error.

のコンパイル時に安心です。 CityLizardの枠組み 提供作成版です。純4.0の製品をご用意しています。のファイルlib/NETFramework4.0/CityLizard.Policy.dll.

でもNuget: https://www.nuget.org/packages/CityLizard/.見 CityLizard.ます。I 構造。

この質問はFAQ一さんの掲示このwiki以降も同様のクにつき意見を表明するものでは古い一;とにかく...

何版。純ます。ご利用の場合.純3.5し 一般事業者の実施MiscUtil (無料です。

このような方法 T Add<T>(T x, T y), その他のvariantのための算数の異なる種類など DateTime + TimeSpan).

また、この作品はすべての組み込み,浮別注事業者は、キャッシュに委譲す。

一部追加の背景になぜこの難であ こちらの.

また、それが知りたい dynamic (4.0)ソートの解消にこの問題を間接的にすぎる

dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect

残念ながらきのみ指定することができる構造体のwhere節でこのインスタンス.でも不思議できないを指定しInt16,Int32。具体的にはがんのある深い実施の理由と配下の決定を許可しない値タイプの場を提供しています。

しないといけないのではないか唯一のソリューションでは、ランタイムを確認する残念なことを防止する問題げがコンパイルす。いくようなもの:-

static bool IntegerFunction<T>(T value) where T : struct {
  if (typeof(T) != typeof(Int16)  &&
      typeof(T) != typeof(Int32)  &&
      typeof(T) != typeof(Int64)  &&
      typeof(T) != typeof(UInt16) &&
      typeof(T) != typeof(UInt32) &&
      typeof(T) != typeof(UInt64)) {
    throw new ArgumentException(
      string.Format("Type '{0}' is not valid.", typeof(T).ToString()));
  }

  // Rest of code...
}

少醜いものの、少なくとも、必要。

私も性能への影響この実装は、おそらくがより早い方法があります。

おそらく、最寄りのままにしかできない

static bool IntegerFunction<T>(T value) where T: struct

だができる以下の

static bool IntegerFunction<T>(T value) where T: struct, IComparable
, IFormattable, IConvertible, IComparable<T>, IEquatable<T>

のためのものでは、なぜだけでなく過負荷のための各種のリストは短いからである少ないメモリフットプリント

することはできない制限するテンプレートの種類が定義することができな行動に基づくタイプです。の一環として汎用の数字パッケージには、その汎用クラスに追加する。

    class Something<TCell>
    {
        internal static TCell Sum(TCell first, TCell second)
        {
            if (typeof(TCell) == typeof(int))
                return (TCell)((object)(((int)((object)first)) + ((int)((object)second))));

            if (typeof(TCell) == typeof(double))
                return (TCell)((object)(((double)((object)first)) + ((double)((object)second))));

            return second;
        }
    }

なお、typeofs評価でコンパイル時間を合算が削除されるコンパイラです。のコンパイラまたスプリアスを削除し咬合でも思いを解決のコンパイラを

        internal static int Sum(int first, int second)
        {
            return first + second;
        }

作ったちっちゃな図書館の機能がこの問題を解決する:

代わりに:

public T DifficultCalculation<T>(T a, T b)
{
    T result = a * b + a; // <== WILL NOT COMPILE!
    return result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.

き書き:

public T DifficultCalculation<T>(Number<T> a, Number<T> b)
{
    Number<T> result = a * b + a;
    return (T)result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Results in 8.

きのソースコードはこちら https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number

私は英語上級者の方にお尋ねしたのと同じsamjudson、なぜだけ整数?その場合は、を作成しても良いでしょうヘルパークラスダイナミックレンジの広いるの種類しています。

だいたい整数のな一般的ですが、実はそうではありません汎用;しみいただけるよう、拒否その他の型を確認す。

何かのポイント。

としての人に指摘されてきて非汎関数の最大の項目、コンパイラが自動的に変換す小さなint値です。

static bool IntegerFunction(Int64 value) { }

場の機能が性能を重視した経路も考え付かないような、IMO(国際海事機関)が過負荷のためのすべての必要な機能

static bool IntegerFunction(Int64 value) { }
...
static bool IntegerFunction(Int16 value) { }

混雑して待たされることなきを取り扱うことができexternaly...

/// <summary>
/// Generic object copy of the same type
/// </summary>
/// <typeparam name="T">The type of object to copy</typeparam>
/// <param name="ObjectSource">The source object to copy</param>
public T CopyObject<T>(T ObjectSource)
{
    T NewObject = System.Activator.CreateInstance<T>();

    foreach (PropertyInfo p in ObjectSource.GetType().GetProperties())
        NewObject.GetType().GetProperty(p.Name).SetValue(NewObject, p.GetValue(ObjectSource, null), null);

    return NewObject;
}

この制限の影響を受けてくれるのを試みた過負荷運営者のための汎用タイプしたがって"INumeric"制約、成功の理由のいい人stackoverflow見の提供、事業定義することができな一般的な種類です。

このような

public struct Foo<T>
{
    public T Value{ get; private set; }

    public static Foo<T> operator +(Foo<T> LHS, Foo<T> RHS)
    {
        return new Foo<T> { Value = LHS.Value + RHS.Value; };
    }
}

私がこの問題。net4動実行時の文字を入力す

public struct Foo<T>
{
    public T Value { get; private set; }

    public static Foo<T> operator +(Foo<T> LHS, Foo<T> RHS)
    {
        return new Foo<T> { Value = LHS.Value + (dynamic)RHS.Value };
    }
}

二つのものを使用 dynamic

  1. ます。すべての値型を得ボックス入り。
  2. ランタイムエラー。You"ビート"をコンパイラがなタイプ。の場合は汎用タイプになっているオペレータ定義の例外がスローされます。

ありませんが"良いソリューションをこなった。ただし絞り込むことができますの型引数を大幅に義missfitsおhypotetical'INumeric'制約としてHaackedは上記に示します。

静bool IntegerFunction<T>(T値がT:IComparable,IFormattable,IConvertible,IComparable<T>,IEquatable<T>、struct {...

きます。純数値のプリミティブ型当の共通インタフェースのため使用されます。ことができるので独自に定義すインタフェース(例: ISignedWholeNumber から行なえるようになり、作業を定義する構造物に含まれるシングル Int16, Int32, など。実施者のインタフェース、およびその方法における汎用型枠 ISignedWholeNumber, がに変換す数値への構造種ると考えられる。

代替的なアプローチを定義するstaticクラス Int64Converter<T> 静的な物件 bool Available {get;}; および静的参加者 Int64 GetInt64(T value), T FromInt64(Int64 value), bool TryStoreInt64(Int64 value, ref T dest).クラスのコンストラクタが使用するハードコーディングへの負荷の代表団は現在までに確認されているの種類、およびその使用を反映するかどうかを試験タイプ T 実施方法の適切な名、署名の場合にはこのようなものstruct載 Int64 とを表す番号は、カスタム ToString() 法です。このアプローチのように特に関連コンパイル時の型チェックがな管理を避けるボクシング業務、各種けする"にチェック"。その後、業務に関連したタイプも交換する委譲を派遣。

ご利用の場合.NET4.0以降をご利用いただけ 動的 方法としての引数をチェック ランタイム時において るのでなければな 動的 引数の型が数値/数の整数タイプです。

場合には、渡された 動的ない 数値/整数値型をスローします。

一例 コードを実装するというようなもの:

using System;
public class InvalidArgumentException : Exception
{
    public InvalidArgumentException(string message) : base(message) {}
}
public class InvalidArgumentTypeException : InvalidArgumentException
{
    public InvalidArgumentTypeException(string message) : base(message) {}
}
public class ArgumentTypeNotIntegerException : InvalidArgumentTypeException
{
    public ArgumentTypeNotIntegerException(string message) : base(message) {}
}
public static class Program
{
    private static bool IntegerFunction(dynamic n)
    {
        if (n.GetType() != typeof(Int16) &&
            n.GetType() != typeof(Int32) &&
            n.GetType() != typeof(Int64) &&
            n.GetType() != typeof(UInt16) &&
            n.GetType() != typeof(UInt32) &&
            n.GetType() != typeof(UInt64))
            throw new ArgumentTypeNotIntegerException("argument type is not integer type");
        //code that implements IntegerFunction goes here
    }
    private static void Main()
    {
         Console.WriteLine("{0}",IntegerFunction(0)); //Compiles, no run time error and first line of output buffer is either "True" or "False" depends on the code that implements "Program.IntegerFunction" static method.
         Console.WriteLine("{0}",IntegerFunction("string")); //Also compiles but it is run time error and exception of type "ArgumentTypeNotIntegerException" is thrown here.
         Console.WriteLine("This is the last Console.WriteLine output"); //Never reached and executed due the run time error and the exception thrown on the second line of Program.Main static method.
    }

もちろん、このソリューションでは、実行時のみでコンパイルす。

したい場合は液を常に作品をコンパイル時にいる時ようにして実行してくださいをラップ 動的 公開struct/クが過負荷 公開 コンストラクタ引数を受け入れの希望する種類のみのstruct/クラスの適切な名前です。

ことは、あってはならないことで巻いた 動的 常に 民間 会員のクラス/構造体では、会員のstruct/クラスの名前をstruct/クラス"の値"となります。

まもって定義および実施 公開 方法および/または事業者が希望する種類の個人動員、クラス構造体が必要です。

ないようにするためにこのstruct/クラス 特に独自の コンストラクタを受け入れる 動的 引数として与えた場合、そのことを初期化しますの民間の動員という"価値"が、 修飾子 このコンストラクタ 民間 のコースです。

一回のクラス/構造体で定義する引数の型のIntegerFunctionするクラス/構造体として定義されています。

一例 コードを実装するというようなもの:

using System;
public struct Integer
{
    private dynamic value;
    private Integer(dynamic n) { this.value = n; }
    public Integer(Int16 n) { this.value = n; }
    public Integer(Int32 n) { this.value = n; }
    public Integer(Int64 n) { this.value = n; }
    public Integer(UInt16 n) { this.value = n; }
    public Integer(UInt32 n) { this.value = n; }
    public Integer(UInt64 n) { this.value = n; }
    public Integer(Integer n) { this.value = n.value; }
    public static implicit operator Int16(Integer n) { return n.value; }
    public static implicit operator Int32(Integer n) { return n.value; }
    public static implicit operator Int64(Integer n) { return n.value; }
    public static implicit operator UInt16(Integer n) { return n.value; }
    public static implicit operator UInt32(Integer n) { return n.value; }
    public static implicit operator UInt64(Integer n) { return n.value; }
    public static Integer operator +(Integer x, Int16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int64 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt64 y) { return new Integer(x.value + y); }
    public static Integer operator -(Integer x, Int16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int64 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt64 y) { return new Integer(x.value - y); }
    public static Integer operator *(Integer x, Int16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int64 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt64 y) { return new Integer(x.value * y); }
    public static Integer operator /(Integer x, Int16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int64 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt64 y) { return new Integer(x.value / y); }
    public static Integer operator %(Integer x, Int16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int64 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt64 y) { return new Integer(x.value % y); }
    public static Integer operator +(Integer x, Integer y) { return new Integer(x.value + y.value); }
    public static Integer operator -(Integer x, Integer y) { return new Integer(x.value - y.value); }
    public static Integer operator *(Integer x, Integer y) { return new Integer(x.value * y.value); }
    public static Integer operator /(Integer x, Integer y) { return new Integer(x.value / y.value); }
    public static Integer operator %(Integer x, Integer y) { return new Integer(x.value % y.value); }
    public static bool operator ==(Integer x, Int16 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int16 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int32 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int32 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int64 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int64 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt16 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt16 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt32 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt32 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt64 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt64 y) { return x.value != y; }
    public static bool operator ==(Integer x, Integer y) { return x.value == y.value; }
    public static bool operator !=(Integer x, Integer y) { return x.value != y.value; }
    public override bool Equals(object obj) { return this == (Integer)obj; }
    public override int GetHashCode() { return this.value.GetHashCode(); }
    public override string ToString() { return this.value.ToString(); }
    public static bool operator >(Integer x, Int16 y) { return x.value > y; }
    public static bool operator <(Integer x, Int16 y) { return x.value < y; }
    public static bool operator >(Integer x, Int32 y) { return x.value > y; }
    public static bool operator <(Integer x, Int32 y) { return x.value < y; }
    public static bool operator >(Integer x, Int64 y) { return x.value > y; }
    public static bool operator <(Integer x, Int64 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt16 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt16 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt32 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt32 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt64 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt64 y) { return x.value < y; }
    public static bool operator >(Integer x, Integer y) { return x.value > y.value; }
    public static bool operator <(Integer x, Integer y) { return x.value < y.value; }
    public static bool operator >=(Integer x, Int16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Integer y) { return x.value >= y.value; }
    public static bool operator <=(Integer x, Integer y) { return x.value <= y.value; }
    public static Integer operator +(Int16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator -(Int16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator *(Int16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator /(Int16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator %(Int16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int64 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt64 x, Integer y) { return new Integer(x % y.value); }
    public static bool operator ==(Int16 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int16 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int32 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int32 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int64 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int64 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt16 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt16 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt32 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt32 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt64 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt64 x, Integer y) { return x != y.value; }
    public static bool operator >(Int16 x, Integer y) { return x > y.value; }
    public static bool operator <(Int16 x, Integer y) { return x < y.value; }
    public static bool operator >(Int32 x, Integer y) { return x > y.value; }
    public static bool operator <(Int32 x, Integer y) { return x < y.value; }
    public static bool operator >(Int64 x, Integer y) { return x > y.value; }
    public static bool operator <(Int64 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt16 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt16 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt32 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt32 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt64 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt64 x, Integer y) { return x < y.value; }
    public static bool operator >=(Int16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int64 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt64 x, Integer y) { return x <= y.value; }
}
public static class Program
{
    private static bool IntegerFunction(Integer n)
    {
        //code that implements IntegerFunction goes here
        //note that there is NO code that checks the type of n in rum time, because it is NOT needed anymore 
    }
    private static void Main()
    {
        Console.WriteLine("{0}",IntegerFunction(0)); //compile error: there is no overloaded METHOD for objects of type "int" and no implicit conversion from any object, including "int", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer(0))); //both compiles and no run time error
        Console.WriteLine("{0}",IntegerFunction("string")); //compile error: there is no overloaded METHOD for objects of type "string" and no implicit conversion from any object, including "string", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer("string"))); //compile error: there is no overloaded CONSTRUCTOR for objects of type "string"
    }
}

が定められた場合において、利用 動的 コードです 追加参照Microsoft.圧倒的な支持を得

バージョン。NET frameworkは以下/小4.0以上 動的 は未定義でバージョンをご利用 オブジェクト 代わりになるには、整数型ではトラブルはあった方がいいと思いまご使用になること。NET4.0以降ができれば利にご利用いただけます 動的 の代わりに オブジェクト.

だいたいは利用 一数値タイプ, き出することが可能となる。うにエイリアスにC++と using.

なのに非常に汎用

T ComputeSomething<T>(T value1, T value2) where T : INumeric { ... }

using MyNumType = System.Double;
T ComputeSomething<MyNumType>(MyNumType value1, MyNumType value2) { ... }

ることができますか doubleint その他、必要な場合にはがすこともございませんがご利用でき ComputeSomethingdoubleint 同プログラム。

かもしれませんがすべて置き換える doubleint しょうか?あなたのメソッドを使用したい double るかどうかの入力は double または int.の別名で知られる変数を使用し 動的 タイプです。

私と似たような状況で必要な対応数字の種類および文字列のように見えるビットの奇妙なミックスがとても苦手なのでお願いします。

再び、多くの人に見てみましょう制約のもいただきましたっインターフェースです。しかし、まだ100%防水およびb)ので、誰にも新しいこのインターネットでの制約が直ちに非常に混乱するからです。

なので、私のアプローチを取り入れて全ての論理への一般法を制約のもと汎用方法です。その後、露出しpublicメソッドは、明示的に取り扱いのたいと思った取扱い-ふと頭に浮かんだのは、コードは清潔で明示的な、例えば

public static string DoSomething(this int input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this decimal input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this double input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this string input, ...) => DoSomethingHelper(input, ...);

private static string DoSomethingHelper<T>(this T input, ....)
{
    // complex logic
}

ありませんシングルまたはインタフェース基底クラスとその継承ではないも継承されたその他のクラス)なので、簡単に答えがno.

いつかこの問題になってる。あけましておめでとうございましたいいおIntegerFunctionクラスでなければできない整数?

いという思いを大切にしてい誤解ジェネリック医薬品.場合に動作しようとする行は特定のデータ型ではないというが、"ジェネリック".

また、みたいなのを作intデータタイプしなが別途必要機能にそれぞれの特定のサイズです。なパラメータの最大の特定の型のプログラムを自動的にupcastのデータ型です。(承Int16までの自動変換しInt64の通話の場合).

の場合を行う業務の実績に基づいてサイズのintてい渡された機能を備えていってくださいというふうに思っておきたい、真剣に考えてもことをしようとしていきた、ということがあります。いる馬鹿にされたと考えるべきかえようとしているの達成はどのようなと考えている。

不おいては、全てのパラメータの型オブジェクトがそのまに申し出なければならないタイプのパラメータの適切な措置を講じまたは例外をスローします。

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