[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;
}
拡張機能のコードはこちら