如何在强制转换中使用 .NET 类型
How to use a .NET Type in a cast
假设一个方法被传递了一个类型。如何在强制转换或关键字 as
.
的右侧使用
文档...System.Type
internal static void Test2()
{
Computer c0 = new Computer("Model Z", 123);
Computer c1 = new Computer("Model Z", 456);
Debug.Assert(c0.Equals(c1));
object o0 = c0;
object o1 = c1;
Debug.Assert(o0.Equals(o1) == false);
Debug.Assert((o0 as Computer).Equals(o1 as Computer));
Debug.Assert(((Computer)o0).Equals((Computer)o1));
Type t = typeof(Computer);
//Debug.Assert((o0 as t).Equals(o1 as t));
//Debug.Assert(((t)o0).Equals((t)o1));
Console.WriteLine("END Test2.");
}
internal class Computer
{
private string Description { get; set; }
private int SerialNumber { get; set; }
internal Computer(string d, int sn) { this.Description = d; this.SerialNumber = sn; }
internal bool Equals(Computer other)
{
return this.Description.Equals(other.Description);
}
}
System.Type
是一个类型的运行时construct/representation。转换是一种编译时构造。基本上,您是在通知编译器您要如何解释内存。所以你问的是不可能的。
如果您真的想让方法采用类型,请考虑使用泛型。
void SomeThing<T>(...)
{
var t = something as T;
}
假设一个方法被传递了一个类型。如何在强制转换或关键字 as
.
文档...System.Type
internal static void Test2()
{
Computer c0 = new Computer("Model Z", 123);
Computer c1 = new Computer("Model Z", 456);
Debug.Assert(c0.Equals(c1));
object o0 = c0;
object o1 = c1;
Debug.Assert(o0.Equals(o1) == false);
Debug.Assert((o0 as Computer).Equals(o1 as Computer));
Debug.Assert(((Computer)o0).Equals((Computer)o1));
Type t = typeof(Computer);
//Debug.Assert((o0 as t).Equals(o1 as t));
//Debug.Assert(((t)o0).Equals((t)o1));
Console.WriteLine("END Test2.");
}
internal class Computer
{
private string Description { get; set; }
private int SerialNumber { get; set; }
internal Computer(string d, int sn) { this.Description = d; this.SerialNumber = sn; }
internal bool Equals(Computer other)
{
return this.Description.Equals(other.Description);
}
}
System.Type
是一个类型的运行时construct/representation。转换是一种编译时构造。基本上,您是在通知编译器您要如何解释内存。所以你问的是不可能的。
如果您真的想让方法采用类型,请考虑使用泛型。
void SomeThing<T>(...)
{
var t = something as T;
}