首页 新闻 会员 周边

dynamic转换类型

0
悬赏园豆:20 [已解决问题] 解决于 2012-08-30 09:25

EntityBase是基类

IBLLBase<T> where T:EntityBase,new() 是基类接口

Test是实体类

TestBLL是接口实现类

下面是某个类里面的的索引

public IBLLBase<dynamic> this[string name]
{
  get
  {
    switch (name.ToLower())
    {
      case"test":
      return (IBLLBase<Test>)new TestBLL();
    }
    return null;
  }
}

错误:Test无法转换成dynamic类型。谁知道怎么做才能把Test转换成dynamic?

|ī笨笨﹎ヤ的主页 |ī笨笨﹎ヤ | 初学一级 | 园豆:2
提问于:2012-08-29 12:47
< >
分享
最佳答案
0

因为你的IBLLBase<T>不支持协变,而且你的T限制了只能是EntityBase,因此答案就是“不能”。话说我很好奇你这么做意义很在,感觉除了测试,没什么用。

收获园豆:20
水牛刀刀 | 大侠五级 |园豆:6350 | 2012-08-29 13:42
其他回答(1)
0
class Base { 
    
    }
    //协变定义,流畅转换成子类型
    interface IBase<out T> where T : Base, new() {
        void SomeMethod();        
    }
    class Derived:Base { 
    
    }
    class Implementation : IBase<Derived> {

        public void SomeMethod()
        {
        }
    }
    class DoSomething {
        //dynamic 不能作为类型参数
        public IBase<Base> this[string name]
        {
            get {
                if (name == "")
                {
                    return new Implementation();
                }
                else
                    return null;
            }
        }
    }
Ethan轻叹 | 园豆:996 (小虾三级) | 2012-08-29 13:54

谢谢 这个可以解决我的问题,但是我想问下。

 

interface IBase<out T> where T : Base, new() {
        void SomeMethod(); 
       List<T> Query();
  }

 

这样子List<T>会报错。

 

 


 

 

支持(0) 反对(0) |ī笨笨﹎ヤ | 园豆:2 (初学一级) | 2012-08-30 09:02

不用了,我解决了。

支持(0) 反对(0) |ī笨笨﹎ヤ | 园豆:2 (初学一级) | 2012-08-30 09:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册