【问题标题】:Create a instance of a class from its string representation of class从类的字符串表示创建类的实例
【发布时间】:2017-06-30 17:01:11
【问题描述】:
string myClass =" public class AcademicTestQuestion { public int Id { get; set; } public string Content { get; set; } public int ContentType { get; set; } public string Descrtionption { get; set; } public bool IsMandatory { get; set; } public bool IsMultiChoice { get; set; } public DateTime InsertDate { get; set; } public DateTime? UpdateDate { get; set; } public bool IsActive { get; set; } public int AcademicTestPageId { get; set; } } ";

以下格式便于阅读

 string myClass ="
    public class AcademicTestQuestion
    {
        public int Id { get; set; }
        public string Content { get; set; }
        public int ContentType { get; set; }
        public string Descrtionption { get; set; }
        public bool IsMandatory { get; set; }
        public bool IsMultiChoice { get; set; }
        public DateTime InsertDate { get; set; }
        public DateTime? UpdateDate { get; set; }
        public bool IsActive { get; set; }
        public int AcademicTestPageId { get; set; }
    }
";

如何在运行时创建上述类的字符串表示的实例并使用?

我正在尝试在运行时将表结构生成到类中。

【问题讨论】:

  • 我认为你应该让你的问题更清楚。你想究竟做什么?
  • 哇。现在这就是我所说的新的。
  • @Recks 不,问题一开始是正确的。他想编译一个在字符串中声明的类。不要弄乱这个问题。虽然存在一些小的语法问题,例如在字符串前面缺少@,但这并不会使问题无效。
  • 我认为您需要在这里解释您要解决的问题类型。即使您设法在运行时编译该类,除了纯 object 实例外,您的程序仍然无法使用它。您可以使用反射(或dynamic)来访问它的属性,但您不能在其他地方声明AcademicTestQuestion 类型的变量。此外,要实际编译它需要做一些工作,所以我会敦促您解释更多,以便我们确定您真的需要树起这棵树。

标签: c#


【解决方案1】:

除非您安装了 C# SDK,否则您无法在运行时执行此操作。

这有点棘手,因为作为开发人员,您通常会安装 C# SDK,因此对您来说它似乎可以工作,但如果您将应用程序部署给用户,则用户通常只有 DotNet已安装运行时环境,但未安装 SDK,因此不适用于他们。

如果您坚持这样做,请从这里开始阅读:

MSDN - System.Runtime.CompilerServices Namespace

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 2012-02-26
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多