Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架中可能具有不同数据类型的对象_C#_Entity Framework_Polymorphism - Fatal编程技术网

C# 实体框架中可能具有不同数据类型的对象

C# 实体框架中可能具有不同数据类型的对象,c#,entity-framework,polymorphism,C#,Entity Framework,Polymorphism,我想使用实体框架在数据库中存储对象,我想让它们存储一些数据和一些头文件。初稿如下: class ResourceAttribute { string AttributeName; DataType DataType; string StringValue; float? FloatValue; int? IntValue; string DefaultStringValue; float? DefaultFloatValue;

我想使用实体框架在数据库中存储对象,我想让它们存储一些数据和一些头文件。初稿如下:

class ResourceAttribute
{
    string AttributeName;
    DataType DataType;

    string StringValue;
    float? FloatValue;
    int? IntValue;

    string DefaultStringValue;
    float? DefaultFloatValue;
    int? DefaultIntValue;
}
class ResourceAttribute<T>
{
    string AttributeName;
    T Value;
    T DefaultValue;
}
这看起来真的很糟糕。有没有更好的方法来表示这样的数据结构

也许是这样的:

class ResourceAttribute
{
    string AttributeName;
    DataType DataType;

    string StringValue;
    float? FloatValue;
    int? IntValue;

    string DefaultStringValue;
    float? DefaultFloatValue;
    int? DefaultIntValue;
}
class ResourceAttribute<T>
{
    string AttributeName;
    T Value;
    T DefaultValue;
}
类资源属性
{
字符串属性名;
T值;
T缺省值;
}
或者使用不同类型的值进行子类化。但这似乎会导致其他问题


以这种方式表示数据的最佳方法是什么?

有多种方法可以实现这一点,其中一种方法是将所有数据存储为字符串,然后通过Convert类对其进行解析,以便:

class ResourceAttribute{
    string AttributeName;
    string Value;
    string DefaultValue;
    Public T GetValue<T>()
    {
      try {
          return Convert.ChangeType(number, typeof(T));
      }
      catch (InvalidCastException) {
         Console.WriteLine("Cannot convert");
         return default(T); // Or you can return your default value obj
      }

    }
}
类资源属性{
字符串属性名;
字符串值;
字符串默认值;
公共T GetValue()
{
试一试{
返回Convert.ChangeType(number,typeof(T));
}
捕获(无效卡斯特例外){
Console.WriteLine(“无法转换”);
返回默认值(T);//或者可以返回默认值obj
}
}
}

这样,通过传递所需的数据类型,可以将其转换为所需的任何格式。所有的值都将以字符串的形式存储在数据库中。

当我遇到类似的问题时,我只使用
对象

public class ResourceAttribute
{
   string AttributeName;
   string DataType;
   object StringValue;
   object DefaultStringValue;
}

您想设置默认值还是默认类型?我想让ResourceAttribute类表示只有一个值的数据,该值可能具有不同的数据类型(string、int或float)以及其他一些始终存在的数据,如Name。对于这个例子来说,默认值并不是那么重要,它是用来说明第一种方法的丑陋性的。我们谈论的是哪种类型,只是简单的基本类型,还是复杂的类?我只是使用简单的基本类型