我有大量的viewmodels,每個都爲一個特定的對象類型(例如Person,Car,whatever)設計。我想爲這些添加通用功能,例如檢查包含特定對象(包含特定Car,Person等)的視圖模型是否已存在的能力。我希望能夠動態創建ViewModel(例如爲Car創建視圖模型,爲Person創建視圖模型)。所有的視圖模型都會有不同的功能,命令等等,所以我不能簡單地使用一個全局視圖模型。有沒有可能爲這個問題使用接口,或者這是一個根本上有缺陷的設計模式?將C#對象作爲通用接口
當前代碼:
namespace DummyNameSpace
{
public interface IViewModel<T>
{
T DataModelObject { get; set; }
string Name { get; set; }
}
public class SomeDataModelObject
{
public string SomeProperty { get; set; }
}
public class ViewModelInstance : IViewModel<SomeDataModelObject> //There will be various ViewModels that implement IViewModel, all with different 'T' types.
{
//Some properties, commands, etc.
}
public class TheMainViewModel //won't implement IViewModel, as this will be used to control all the various other viewmodels.
{
public void MethodBeingCalled(object viewmodelinstance)
{
Type type = viewmodelinstance.GetType();
var x = (viewmodelinstance as IViewModel<type>).DataModelObject = null; //Will do other things here.
}
}
}
當前的代碼不工作,因爲我不能用 「X作爲IViewModel(型)」。是否有不同的拳擊方式'x',以便我可以通過界面訪問它?
'var x = viewModelInstance.DataModelObject = null;'雖然沒有意義。 'x'將始終爲'null' –
@SriramSakthivel是的,我在你發表評論之前就擺脫了它一秒鐘:D – Luaan
添加'null'是我身邊的一個糟糕的例子:-)這正是我正在尋找,我已經實施。謝謝! –