Generics where T is class implementing interface

人盡茶涼 提交于 2019-12-05 11:50:20

问题


I have a interface:

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!

However everything compiles, and only runtime errors is thrown by the XmlSerializer.

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

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?


回答1:


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

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

where T : class, IProfile, new()



回答2:


Works for me

public interface IUser
{
    int AthleteId { get; set; }
    string GivenName { get; set; }
    string FamilyName { get; set; }         
    bool IsActive { get; set; }
}

public  class DjsNameAutoSearch<Result, User> : where User : class, IUser, new()


来源:https://stackoverflow.com/questions/22247573/generics-where-t-is-class-implementing-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!