[Serializable]
public abstract class A
{
public A()
{
}
}
[Serializable]
public class B : A
{
public B() : base()
{
}
}
在扩展中:
public static T NextRecord<T>(this SqlDataReader reader) where T : A, new()
{
// Do work
}
我这样称呼这个扩展:
B b = reader.NextRecord<B>();
然而,我得到了这个例外:“没有从'B'到'A'的隐式引用转换。”
我究竟做错了什么?
谢谢。
编辑
public static T NextRecord<T>(this SqlDataReader reader) where T : A, new()
{
// Make sure we have been given a correct Type
if (!typeof(T).BaseType.Equals(typeof(A)))
{
throw new Exception("Supplied Type is not derived from Type A");
}
if (reader.IsNull())
{
throw new ArgumentNullException("reader is null");
}
if (reader.HasRows)
{
if (reader.Read())
{
// Instance a object of the type, passing it the SqlDataReader so that it can populate itself
return Activator.CreateInstance(typeof(T), new object[] { reader }) as T;
}
}
return null;
}
这是扩展的代码