我读过"UnderlyingSystemType“的定义,即它”表示公共语言运行库提供的表示此类型的类型“。
在When does the UnderlyingSystemType differ from the current Type instance的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));当运行时,我只得到一堆trues。
我的问题是,是否存在对象的底层系统类型可以与其类型不同的情况?这种区别的目的是什么,仅仅是为了允许定义不能实例化的假设类型吗?我甚至不能使用new关键字创建一个新的类型。而且Type的所有属性都是get-only的,所以我不知道这个特性是做什么的。这种区别在其他语言中可能有用吗?
发布于 2012-11-25 22:39:45
Type是一个抽象类。您将看到的最常见的实现是RuntimeType,这是典型的对象,但是任何人都可以创建Type的实现。RuntimeType的UnderlyingSystemType将返回相同的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);
}
}
}https://stackoverflow.com/questions/13551691
复制相似问题