将所述类型参数动态地传递给泛型类型

本文关键字:泛型类型 动态 类型参数 | 更新日期: 2023-09-27 18:00:30

public class Access
{
    public Entity eeee { get; set; }
    public Permission<eeee.GetType()> pppp { get; set; }
}
public class Entity
{
}
public class Permission<T>
{
    public bool CanView {get;set;}
    public bool CanEdit {get;set;}
    public bool CanDelete {get;set;}
}
public class Photo:Entity
{
}
public class PhotoPermission:Permission<Photo>
{
    public bool CanTag {get;set;}
}
public class Video:Entity
{
}
public class VideoPermission:Permission<Video>
{
    public bool CanFastForward {get;set;}
}

因此,如果eeee是类型Photo,那么pppp的"类型"应该是Permission<Photo>

有类似eeee.GetType() 的东西吗

将所述类型参数动态地传递给泛型类型

看起来您可以很容易地将Access类更改为

public class Access<T>
{
    public T eeee { get; set; }
    public Permission<T> pppp { get; set; }
}
泛型背后的思想是泛型类型在运行时是已知的;因此,您的代码不会编译。我建议你使用反射来完成你的任务。