【问题标题】:passing the type parameter dynamically to a generic type将类型参数动态传递给泛型类型
【发布时间】:2011-06-24 11:49:17
【问题描述】:
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&lt;Photo&gt;

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

【问题讨论】:

  • 为什么不能把public Permission&lt;eeee.GetType()&gt; pppp { get; set; }改成public Permission&lt;Entity&gt; pppp { get; set; }

标签: c# generics oop


【解决方案1】:

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

public class Access<T>
{
    public T eeee { get; set; }
    public Permission<T> pppp { get; set; }
}

【讨论】:

    【解决方案2】:

    泛型背后的想法是泛型类型在运行时是已知的;因此,您的代码将无法编译。我建议你使用反射来完成你的任务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2017-12-23
      • 2010-11-15
      • 2016-02-12
      • 1970-01-01
      相关资源
      最近更新 更多