【问题标题】:C# value assignment to object reference directly直接将 C# 值赋值给对象引用
【发布时间】:2019-02-15 23:23:48
【问题描述】:
Person p = "Any Text Value";

人是一个类。

这在 C# 中是否可行。

我的回答是不,但根据面试官的说法,这是可能的。他也没有给我任何线索。

【问题讨论】:

    标签: c# .net assignment-operator


    【解决方案1】:

    您可以使用implicit conversion 实现此目的。可以说这是对隐式转换的滥用,因为在这种情况下"Any Text Value" 应该代表什么并不明显。这是使您的示例成功的代码示例:

    public class Person
    {
        public string Name { get; set; }
    
        public static implicit operator Person(string name) =>
            new Person { Name = name }; 
    }
    

    这是一个.NET Fiddle 示例。

    【讨论】:

      【解决方案2】:

      这可以使用implicit 来完成,如下所示:

      using System;
      
      namespace Demo
      {
          public sealed class Person
          {
              public Person(string name)
              {
                  Name = name;
              }
      
              public static implicit operator Person(string name)
              {
                  return new Person(name);
              }
      
              public string Name { get; }
          }
      
          static class Program
          {
              static void Main()
              {
                  Person person = "Fred";
      
                  Console.WriteLine(person.Name);
              }
          }
      }
      

      但是,首选显式转换 - 您通常应该only use implicit for things like inventing a new numeric type such as Complex

      【讨论】:

        猜你喜欢
        • 2013-07-13
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 2021-08-28
        • 2013-11-24
        相关资源
        最近更新 更多