泛型T是类实现的接口 [英] Generics where T is class implementing interface

查看:368
本文介绍了泛型T是类实现的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口:

interface IProfile { ... }

...和类:

...and a class:

[Serializable]
class Profile : IProfile 
{ 
  private Profile()
  { ... } //private to ensure only xmlserializer creates instances
}

...和方法的经理:

...and a manager with method:

class ProfileManager
{
  public T Load<T>(string profileName) where T : class, IProfile
  {
    using(var stream = new .......)
    {
      var ser = new XmlSerializer(typeof(T));
      return (T)ser.Deserialize(stream);
    }
  }
}

我希望使用这样的方法:

I expect the method to be used like this:

var profile = myManager.Load<Profile>("TestProfile"); // class implementing IProfile as T

...扔编译在这个时候错误:

...and throw compile time error on this:

var profile = myManager.Load<IProfile>("TestProfile"); // NO! IProfile interface entered!

不过一切编译,只有运行时错误被抛出的XmlSerializer

我想到了其中T:类将确保在那里只接受类类型

I thought the where T : class would ensure only class types where accepted?

是否有可能使编译器抛出一个异常 IProfile (或其他接口从 IProfile继承)进入,只有类型的课程实施 IProfile 接受?

Is it possible to make the compiler throw error if IProfile (or other interfaces inheriting from IProfile) is entered, and only types classes implementing IProfile are accepted?

推荐答案

根据 MSDN 类意味着T必须是引用类型;这也适用于任何类,接口,委托或数组类型。

According to MSDN class means that T must be a reference type; this applies also to any class, interface, delegate, or array type.

一个解决办法是要求那件T实现了参数较少的构造函数,因此:

One work around would be to require that T implements the parameter less constructor so:

where T : class, IProfile, new()

这篇关于泛型T是类实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆