Console.WriteLine()方法

本文探讨了在C#编程中如何通过重写object类的ToString()方法来实现对象的字符串表示,以及自动调用ToString()方法的情况。重点讲解了string类作为sealed类不能被继承和override其ToString()方法的特性。

今天看到一段代码:

    namespace ConsoleApplication2
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        //重写object类的ToString()方法,string类是sealed类,不能override.
       public override string ToString()
        {
            return "Person: " + Name + " " + Age;
        }
     
      
    }

    class Program

    {
       
         static void Main(string[] args)
        {
            Person person1 = new Person { Name = "John", Age = 12 };
            Console.WriteLine(person1);    //会自动调用ToString()方法。
            Console.WriteLine(person1.Name.ToString());
            Console.WriteLine(person1.ToString());
        }
    }
}

Console.WriteLine(object)时,会自动调用ToString()方法的。因为string是sealed类,所以被inhrets.不能被inhrets就不能override它的ToString()方法了。

当 `CSharpCompilation` 的 `OutputKind` 为 `DynamicallyLinkedLibrary` 时无法使用 `Console.WriteLine` 方法,通常是因为缺少对 `System.Console` 所在程序集的引用。以下是解决办法: ### 确保引用 `System.Console` 所在的程序集 在创建 `CSharpCompilation` 时,需要添加对 `System.Console` 所在程序集的引用,即 `System.Console.dll`。以下是示例代码: ```csharp using System; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; class Program { static void Main() { // 定义源代码 SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@" using System; namespace DynamicDllSample { public class ConsoleWriter { public void WriteMessage() { Console.WriteLine(""This is a test message.""); } } }"); // 生成随机的程序集名称 string assemblyName = Path.GetRandomFileName(); // 添加必要的引用 MetadataReference[] references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Console).Assembly.Location) // 添加对 System.Console 程序集的引用 }; // 创建 CSharpCompilation 实例 CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); // 内存流用于存储编译结果 using (var ms = new MemoryStream()) { // 进行编译 EmitResult result = compilation.Emit(ms); if (result.Success) { ms.Seek(0, SeekOrigin.Begin); // 加载编译后的程序集 Assembly assembly = Assembly.Load(ms.ToArray()); // 获取类型 Type type = assembly.GetType("DynamicDllSample.ConsoleWriter"); if (type != null) { // 创建实例 object instance = Activator.CreateInstance(type); // 获取方法 MethodInfo method = type.GetMethod("WriteMessage"); if (method != null) { // 调用方法 method.Invoke(instance, null); } } } else { // 输出编译错误信息 var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (var diagnostic in failures) { Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage()); } } } } } ``` ### 解释 1. **添加引用**:通过 `MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)` 添加对 `System.Console` 程序集的引用,确保编译器能够找到 `Console.WriteLine` 方法。 2. **编译并加载程序集**:使用 `CSharpCompilation` 进行编译,并将编译结果存储在内存流中,然后使用 `Assembly.Load` 方法加载编译后的程序集。 3. **调用方法**:通过反射获取类型方法,并调用 `WriteMessage` 方法,该方法中包含 `Console.WriteLine` 调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值