且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#泛型错误-类型字符串必须不可为空

更新时间:2022-05-17 03:26:39

有一个约束条件:

public abstract class Entity<T> : IEntity where T : struct

所以string不是struct的类型,string是引用类型. .NET中的struct和class有什么区别?

so string is not type of struct, string is a reference type. What's the difference between struct and class in .NET?

正如msdn所说:

约束会通知编译器有关类型参数的功能 一定有.没有任何约束,类型参数可以是任何 类型.编译器只能假定System.Object的成员, 是任何.NET类型的最终基类.欲获得更多信息, 请参阅为什么要使用约束条件.

Constraints inform the compiler about the capabilities a type argument must have. Without any constraints, the type argument could be any type. The compiler can only assume the members of System.Object, which is the ultimate base class for any .NET type. For more information, see Why use constraints.

您可以删除此约束以避免发生此错误,现在您的Id可以是任何类型:

You can remove this constraint to avoid this error and now your Id can be any type:

public abstract class Entity<T> : IEntity

作为string类型的密钥的替代方案,如果它适合您的情况,则可以创建T类型的Guid.如果它可以是Guid类型,则可以避免删除约束:

As an alternative to string type of key and if it is eligible for your case, you can create T type of Guid. If it can be type of Guid, then you can avoid deletion of constraint:

public abstract class FullAuditedEntity<T> : IFullAuditedEntity where T : struct
{
     // ... The code is omitted for the brevity
}

和您的实体:

[Table(name: "Status")]
public class Status : FullAuditedEntity<string>
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Required]
    [Guid]
    public override Guid Id { get; set; }