我正在尝试创建两个接口层次结构,一个用于业务模型对象,另一个用于ui。我知道在层之间松耦合很重要,但是应用程序的一部分需要绘图,所以我需要模型对象随时可用于相应的图形表示,并且我有一个公共层保存模型对象的接口。 / p>
公共类库代码:
public interface IBase {}
public interface IBookObject : IBase {}
public interface ITapeObject : IBase {}
public class Book : IBookObject {}
图形图层代码:
public interface IModelObject<T>
{
T ModelObject { get; set; } // might be a book or tape , etc
}
public class GraphicObject<T> : IModelObject<T>
{
public T ModelObject { get; set; }
}
代码使用:
IBookObject bk = new Book();
var go = new GraphicObject<IBookObject>(); // will fail later
//var go = new GraphicObject<IBase>(); // will succeed later
go.ModelObject = bk;
if (go is IModelObject<IBase>) // can't use is IModelObject<IBookObject>
// as go might be GraphicObject<ITapeObject>
{
Debug.WriteLine("Success");
}
因此,如果我想测试IBase(然后访问ModelObject),我必须确保原始对象是使用IBase而不是派生接口创建的,这似乎是以后出错的原因。我的问题是:
1)我做的事情可怕吗?! :)我可能会忽略一个更好的方法..
2)如果失败了,是否有某种方法可以使用新的逆变c#4技术对任何来自IBase的界面进行线性测试?或者我认为如果IBook没有从IBase继承,它会起作用,但Book(和Tape)分别实现了IBook和IBase。
3)如果失败,有没有办法阻止GraphicObject<IBookObject>()
和GraphicObject<ITapeObject>()
的构建?
谢谢!
答案 0 :(得分:0)
这会有用吗?
public interface IBase { }
public interface IBookObject : IBase { }
public interface ITapeObject : IBase { }
public class Book : IBookObject { }
public interface IModelObject
{
IBase ModelObject { get; set; } // might be a book or tape , etc
}
public class GraphicObject<T> : IModelObject
where T: class, IBase
{
public T ModelObject { get; set; }
#region IModelObject Members
IBase IModelObject.ModelObject
{
get
{
return ModelObject;
}
set
{
ModelObject=value as T;
}
}
#endregion
}
class Program
{
static void Main(string[] args)
{
IBookObject bk=new Book();
var go=new GraphicObject<IBookObject>(); // will fail later
//var go = new GraphicObject<IBase>(); // will succeed later
go.ModelObject=bk;
if(go is IModelObject) // can't use is IModelObject<IBookObject> as go might be GraphicObject<ITapeObject>
{
Debug.WriteLine("Success");
}
}
}