3

「UnderlyingSystemType」の定義、つまり「この型を表す共通言語ランタイムによって提供される型を示す」という定義を読みました。

UnderlyingSystemTypeが現在のTypeインスタンスと異なるのはいつですかというSOの関連リンクがありますが、UnderlyingSytemTypeとは異なるタイプのオブジェクトを持つことが実際に可能かどうかは答えからわかりません。

最近、CLS 準拠について知りましたが、unsigned int は CLS に準拠していません。そして、CLS に準拠していない型の基になる型が異なる可能性があるのではないかと期待していましたが、そうではありませんでした。

価値のあるものとして、私がテストに使用したコードは次のとおりです。

Byte    t01 = 1;
SByte   t02 = 1;
Int16   t03 = 1;
UInt16  t04 = 1;
Int32   t05 = 1;
UInt32  t06 = 1;
Int64   t07 = 1;
UInt64  t08 = 1;
Single  t09 = 1;
Double  t10 = 1;
Decimal t11 = 1;
Console.WriteLine(t01.GetType().Equals(t01.GetType().UnderlyingSystemType));
Console.WriteLine(t02.GetType().Equals(t02.GetType().UnderlyingSystemType));
Console.WriteLine(t03.GetType().Equals(t03.GetType().UnderlyingSystemType));
Console.WriteLine(t04.GetType().Equals(t04.GetType().UnderlyingSystemType));
Console.WriteLine(t05.GetType().Equals(t05.GetType().UnderlyingSystemType));
Console.WriteLine(t06.GetType().Equals(t06.GetType().UnderlyingSystemType));
Console.WriteLine(t07.GetType().Equals(t07.GetType().UnderlyingSystemType));
Console.WriteLine(t08.GetType().Equals(t08.GetType().UnderlyingSystemType));
Console.WriteLine(t09.GetType().Equals(t09.GetType().UnderlyingSystemType));
Console.WriteLine(t10.GetType().Equals(t10.GetType().UnderlyingSystemType));
Console.WriteLine(t11.GetType().Equals(t11.GetType().UnderlyingSystemType));

実行すると、たくさんの真実が得られます。

私の質問は、オブジェクトの基になるシステム タイプがそのタイプと異なる場合があるということです。そして、この区別の目的は何ですか?インスタンス化できない仮想型の定義を許可するだけですか? new キーワードを使用して新しいタイプを作成することさえできません。また、Type のすべてのプロパティは取得専用であるため、この機能が何をするのかわかりません。この区別は他の言語でも役立つのでしょうか?

4

1 に答える 1

3

Type抽象クラスです。あなたが目にする最も一般的な実装は でありRuntimeType、これは通常のオブジェクトですが、誰でも の実装を作成できますType。 は同じものを返しRuntimeTypeます。私が見た限り、これは、オブジェクトを取得して を呼び出す場合ではなく、そのような型をローカルで取得する or を構築するメソッドがある場合にのみ、本当に重要です。理解に役立つ例を次に示します。UnderlyingSystemTypeRuntimeTypeTypeGetType

class Program
{
    static void Main(string[] args)
    {
        // creates a type whose methods and properties are all like Int32, but with an UnderlyingSystemType of string
        var type = new MyType(typeof(int));
        Console.WriteLine(type.FullName); // prints System.Int32
        Console.WriteLine(type.UnderlyingSystemType.FullName); // prints System.String
    }
}
class MyType : TypeDelegator //this extends Type, which is an abstract class
{
    public MyType(Type t) : base(t) { }
    public override Type UnderlyingSystemType
    {
        get
        {
            return typeof(string);
        }
    }
}
于 2012-11-25T14:39:44.570 に答える