我有以下界面和抽象类型:
public interface IByteSerializer<T> {...}
public abstract class ByteSerializer<T> : IByteSerializer<T> {...}
public sealed class UIDSerializer : ByteSerializer<UID> {...}
我希望能够使用下面的静态泛型方法返回接口:
public abstract class SerializableObject<T> : IByteSerializable<T>
{
// ...
public static IByteSerializer<T> GetTypeSerializer()
{
if (typeof(T) == typeof(UID)) { return new UIDSerializer() as IByteSerializer<T>; }
// else if...
throw new TypeAccessException("An IByteSerializer does not exist for type " + typeof(T) + ".");
}
}
为什么我不能return new UIDSerializer();
?尝试这样做失败,错误:
CS0029 Cannot implicitly convert type UIDSerializer to IByteSerializer<T>
我能够让这个工作的唯一方法是使用as
运算符,如上所述 - 这确实有效。但是,明确的(cast)
也会失败。如果我尝试:
return (IByteSerializer<T>)new UIDSerializer();
我同时收到cannot convert type
错误和cast is redundant
警告。这些似乎完全相互矛盾!
我思考的失误在哪里?
更新
从sealed
类中删除UIDSerializer
修饰符可让我成功将返回类型转换为IByteSerializer<T>
。那么这个修饰符与演员有什么关系?
public class UIDSerializer : ByteSerializer<UID> {...} // not sealed
允许
return (IByteSerializer<T>)new UIDSerializer();