【问题标题】:How to use a .NET Type in a cast如何在演员表中使用 .NET 类型
【发布时间】:2021-02-22 02:01:30
【问题描述】:

假设一个方法被传递了一个类型。如何在演员表或关键字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);
    }
}

【问题讨论】:

  • 可以创建将对象转换为指定类型的表达式树,将表达式树编译为委托,然后能够将对象传递给委托。但这可能不是你想要的。

标签: .net casting system.type


【解决方案1】:

System.Type 是一种类型的运行时构造/表示。强制转换是一种编译时构造。基本上你是在告诉编译器你想如何解释内存。所以你问的是不可能的。

如果你真的想让一个方法接受一个类型,可以考虑使用泛型。

void SomeThing<T>(...)
{
   var t = something as T;
}

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2020-05-01
    • 2019-12-02
    相关资源
    最近更新 更多