类中未定义类型的 C# 属性
本文关键字:属性 类型 未定义 | 更新日期: 2023-09-27 18:32:39
我想用 C# 创建一些类(假设它是 class Attribute)
public class Attribute
{
public int ID { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
此类的实体将具有 ID、名称和值属性。
主要问题是我想在属性中保存 值 不同类型的数据:字符串、整数、双精度、日期时间等。
制作这样的解决方案的最佳方法是什么?
您正在寻找泛型类型?
public class Attribute<T>
{
public int ID {get; set;}
public string Name { get; set; }
public T Value { get; set; }
}
编辑:
public void SomeMethod()
{
var attribute = new Attribute<int>(){ ID = 1, Name = "TheName", Value = 46 };
}
Usuage 会是这样的
int result =10;
Attribute<int> objAttribute = new Attribute<int>();
objAttribute.value = result;
string strResult ="Sucess";
Attribute<string> objAttribute1 = new Attribute<string>();
objAttribute1.value = strResult ;