我是 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/