如何为属性创建自己的数据类型

时间:2016-10-11 14:44:14

标签: c# types

我有一个Invoice,其中包含要由用户完成的特定字段并将其保存在数据库中。此特定字段具有名称和值。该值可以是text,date,int或将来的其他类型,我必须可扩展。

Example:
Invoice 1, ParticularField 1, "Hello world"
Invoice 2, ParticularField 1, "Bye bye"
Invoice 3, ParticularField 2, 1234
Invoice 4, ParticularField 2, 5678

如何从“ParticularFieldValue”类中获取“ParticularField”的值来完成此值。

Diagram

2 个答案:

答案 0 :(得分:0)

您可以将数据作为纯对象返回,然后将其转换为Type。

class FieldValue
{
    private object data;
    private Type type;

    public object Data
    {
        get { return data; }

        set
        {
            data = value;
            type = value.GetType();
        }
    }

    public Type Type
    {
        get { return type; }
    }
}

答案 1 :(得分:0)

不确定这是否是你想要的,但这里什么都没有:

class Program
{
    static void Main(string[] args)
    {
        string name1 = "ParticularField 1";
        string name2 = "ParticularField 2";
        string name3 = "ParticularField 3";

        string value1 = "this is a string";
        int value2 = 12345;
        DateTime value3 = DateTime.Today;

        ParticularField pf1 = new ParticularField(name1, value1, value1.GetType());
        ParticularField pf2 = new ParticularField(name2, value2, value2.GetType());
        ParticularField pf3 = new ParticularField(name3, value3, value3.GetType());

        Console.WriteLine("Name: " + pf1.GetName());
        Console.WriteLine("Value: " + pf1.Value);
        Console.WriteLine("Type: " + pf1.ValueType);
        Console.WriteLine();

        Console.WriteLine("Name: " + pf2.GetName());
        Console.WriteLine("Value: " + pf2.Value);
        Console.WriteLine("Type: " + pf2.ValueType);
        Console.WriteLine();

        Console.WriteLine("Name: " + pf3.GetName());
        Console.WriteLine("Value: " + pf3.Value);
        Console.WriteLine("Type: " + pf3.ValueType);
        Console.WriteLine();

        Console.Read();
    }
}
public class ParticularField
{
    string Name;
    public object Value { get; }
    public Type ValueType { get; }
    public string GetName() { return Name; }
    public ParticularField (string name, object value, Type type)
    {
        Name = name;
        Value = value;
        ValueType = type;
    }
}