【问题标题】:How to define a type whose gender can be changed on the fly in code without changing the type of all the properties that are of its type?如何定义一个类型,其性别可以在代码中动态更改而不更改其类型的所有属性的类型?
【发布时间】:2021-08-07 03:35:32
【问题描述】:

我有许多实体使用相同类型的 UserId 属性。

我能否定义一个类型(字符串或 int,...),我可以轻松地将其更改为所有人的变体?

例子:

public class Entity_One
{
    public DefineMyType UserId { get; set; }
    public string Property_Entity_One { get; set; }
}

public class Entity_Two
{
    public DefineMyType UserId { get; set; }
    public string Property_Entity_Two { get; set; }
}

const DefineMyType = string;
// or const DefineMyType = int;
// or const DefineMyType = Guid;

【问题讨论】:

  • 可以是id也可以不是。例子:在表User中,是id;在另一个表中,它是外键。如果我在 User 中编辑 UserId 的类型(字符串到 int),我必须编辑所有关系表。所以,我想定义一个DefineMyType。然后如果在User中编辑UserId的类型,我只编辑DefineMyType
  • 为什么不呢?你试过了吗?

标签: c# generics types parameters uniqueidentifier


【解决方案1】:

不能这样使用常量。

可以使用预处理器。

但我们可以使用泛型:

public abstract class AbstractID<T>
{
  static protected T Last = default;
  public T Value { get; protected set; } // or perhaps init only with C# 9
}

因此我们可以定义一些专门的 ID,例如:

public class NumberID<T> : AbstractID<T> where T : struct, IComparable, IFormattable
{
  public NumberID()
  {
    Value = (T)( (dynamic)Last + 1 );
    Last = Value;
  }
}

public class GuidID : AbstractID<Guid>
{
  public GuidID()
  {
    Value = Guid.NewGuid();
    Last = Value;
  }
}

public class StringID : AbstractID<string>
{
  private string Generate()
  {
    return ...
  }
  public StringID()
  {
    Value = Generate();
    Last = Value;
  }
}

然后我们可以设置“默认”ID类型:

public class ManagedID : NumberID<int>
{
}

或者:

public class ManagedID : GuidID
{
}

因此,我们可以轻松地为所有使用它的代码更改 ManagedID。

只需要修改声明中的祖先类。

现在可以了:

public class EntityOne
{
  public ManagedID UserId { get; } = new ManagedID();
  public string PropertyEntityOne { get; set; }
}

public class EntityTwo
{
  public ManagedID UserId { get; } = new ManagedID();
  public ManagedID EntityOneId { get; }
  public string PropertyEntityTwo { get; set; }
  public EntityTwo(EntityOne one)
  {
    EntityOneId = one.UserId;
  }
}

测试

var entity1 = new EntityOne();
var entity2 = new EntityOne();
var entity3 = new EntityTwo(entity1);
Console.WriteLine(entity1.UserId.Value);
Console.WriteLine(entity2.UserId.Value);
Console.WriteLine(entity3.UserId.Value + $" ({entity3.EntityOneId.Value})");

结果为整数

1
2
3 (1)

带有 GUID 的结果

3a189122-60fd-4dc5-9d7f-3cc4c83375f9
37a9c7de-8ed5-4d02-a1b9-f414db051335
2de962d6-cc91-4e78-b3dc-28acb0ba7f3b (3a189122-60fd-4dc5-9d7f-3cc4c83375f9)

警告

在这里,数字的使用是非常基本的并且不是真正可靠的,尤其是在本地机器之外并且在停止执行当前进程之后。因此,对于一个真实的数据库来说,最后一个值的某个地方需要持久性,比如在配置文件或其他任何地方。

GUID vs INT IDENTITY

Guid vs INT - Which is better as a primary key?

Int for identity/primary key and Guid for public identifier, best practices?

【讨论】:

    猜你喜欢
    • 2011-04-15
    • 1970-01-01
    • 2016-12-11
    • 2017-03-04
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多