首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GetType()和GetType().UnderlyingSystemType的区别

GetType()和GetType().UnderlyingSystemType的区别
EN

Stack Overflow用户
提问于 2012-11-25 21:58:34
回答 1查看 1.6K关注 0票数 3

我读过"UnderlyingSystemType“的定义,即它”表示公共语言运行库提供的表示此类型的类型“。

When does the UnderlyingSystemType differ from the current Type instance的SO上有一个相关的链接,但我不能从答案中判断出是否真的可能有一个类型与UnderlyingSytemType不同的对象。

我最近了解到CLS遵从性,而unsigned int并不符合CLS。我真的希望这可以做到,不符合CLS的类型可能会有不同的底层类型,但事实并非如此。

无论如何,我用来测试的代码是:

代码语言:javascript
复制
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));

当运行时,我只得到一堆trues。

我的问题是,是否存在对象的底层系统类型可以与其类型不同的情况?这种区别的目的是什么,仅仅是为了允许定义不能实例化的假设类型吗?我甚至不能使用new关键字创建一个新的类型。而且Type的所有属性都是get-only的,所以我不知道这个特性是做什么的。这种区别在其他语言中可能有用吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-25 22:39:45

Type是一个抽象类。您将看到的最常见的实现是RuntimeType,这是典型的对象,但是任何人都可以创建Type的实现。RuntimeTypeUnderlyingSystemType将返回相同的RuntimeType。据我所知,只有当你有一个接受Type或在本地构造这样的类型的方法时,这才是真正有意义的,而不是如果你获得一个对象并调用GetType。这里有一个例子来帮助你理解:

代码语言:javascript
复制
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);
        }
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13551691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档