gpt4 book ai didi

c# - GetType() 和 GetType().UnderlyingSystemType 之间的区别

转载 作者:行者123 更新时间:2023-11-30 16:21:04 27 4
gpt4 key购买 nike

我已经阅读了“UnderlyingSystemType”的定义,即它“表示公共(public)语言运行时提供的表示此类型的类型”。

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

我最近了解了 CLS 合规性,并且 unsigned int 不符合 CLS。我真的希望这可能会做到这一点,非 CLS 兼容类型可能具有不同的基础类型,但事实并非如此。

就其值(value)而言,我用来测试的代码是:

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));

运行时,我只得到一堆 true。

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

最佳答案

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

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);
}
}
}

关于c# - GetType() 和 GetType().UnderlyingSystemType 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com