c# - 如何打印通用对象的属性

标签 c# generics

我是 C# 初学者,正在尝试一段新代码。以下代码未正确打印值:

namespace systemTypes
{
    class Program
    {
        static void Main(string[] args)
        {
             CommonData<string>name = new CommonData<string>();
             name.Value = "abcd";
             CommonData<float>version = new CommonData<float>();
             version.Value = 2.0F;
             Console.WriteLine(
                 "generic object storing string val : {0}",
                 name.Value);
             Console.WriteLine(
                 "generic object storing float val : {0}",
                 version.Value);
         }
    }

    public class CommonData<T>
    {
        private T _data;
        public T Value
        {
            get
            {
                return this._data;
            }
            set
            {
                this._data = value;
            }
        }
    }
}

它向控制台打印字符串值的空白和整数值的零。我需要实现默认构造函数吗?我在这里缺少什么?

最佳答案

编译器会告诉你这是错误的:

CommonData<int>version = new CommonData<float>();

编译器说:

Error 1 Cannot implicitly convert type 'systemTypes.CommonData' to 'systemTypes.CommonData' some.cs 10 39 someproject

目前它无法编译,因此您正在运行某个可能硬编码为零的旧版本。您没有运行显示的代码。

工作代码应该是:

CommonData<float>version = new CommonData<float>();

但是,有时候说太多是自找麻烦; var 第一次就可以正常工作:

var name = new CommonData<string>();
name.Value = "abcd";
var version = new CommonData<float>();
version.Value = 2.0F;
Console.WriteLine("generic object storing string val : {0}", name.Value);
Console.WriteLine("generic object storing float val : {0}", version.Value);

这里,var 只是意味着“编译器:你可以看到右边的内容——请你帮我算出变量类型”。它并不意味着“变体”或“动态”或类似的东西。

关于c# - 如何打印通用对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11890580/

相关文章:

java - 在 Java Collections Map<Key,?> 中 "?"指的是什么?

java - 在 Java 8 中创建通用谓词

c# - 如何使用 C# 将 DateTime 对象转换为仅包含日期的字符串?

c# - 如何比较今天的给定日期

java - 如何使用泛型和反射来减少代码

Swift 泛型和协议(protocol)关联类型

java - 什么时候在 Java 中进行类型检查

c# - 反序列化来自 Facebook 的数据

c# - 我可以让 Json.net 使用 "primary"构造函数反序列化 C# 9 记录类型,就好像它有 [JsonConstructor] 一样?

c# - 使用 var/null 奇怪的行为进行切换