Generic object for two different classes

时间:2015-10-30 23:38:35

标签: c#

I have a class for my acquisition device. Then I want to create another class that generates random samples for when my acquisition device is not connected. This is my object: private object AmplifierObj; And I want a create it like that if (AmpSettingsObj.DaqDevice == "noAmp") AmpObj = new NoAmpManager(sampleRate: sampleRate); else AmpObj = new USBampManager(optCalibrationFlag: calibrationFlag, serialNumbers: serialNumbers, sampleRate: sampleRate); However, when I call one of the methods I get the error "object" does not contain a definition for the method . Both classes have exactly the same methods implemented. What would be the best way of implementing it? Should I use a generic class as a placeholder?

2 个答案:

答案 0 :(得分:1)

If both classes have the same methods you should have an interface (IAmplifier) and both classes should implement this interface. This can be easily done by right clicking one of the classes and selecting Refactor / Extract Interface. Assuming your interface name is IAmplifier, have both classes implement the same interface such as: public class NoAmpManager : IAmplifier { ... (Methods) ... (Properties) } public class USBampManager : IAmplifier { ... (Methods) ... (Properties) } Then, instead of private object AmplifierObj; Use private IAmplifier AmplifierObj;

答案 1 :(得分:0)

You can do it like this public class AmplifierObj { public Object AnySameProperty { get; set; } } public class NoAmpManager: AmplifierObj { public void Foo() { } } public class USBampManager : AmplifierObj { public void Bar() { } } But always must call the sub class property you should check object type AmplifierObj AmpObj; if (AmpSettingsObj.DaqDevice == "noAmp") AmpObj = new NoAmpManager(sampleRate: sampleRate); else AmpObj = new USBampManager(optCalibrationFlag: calibrationFlag, serialNumbers: serialNumbers, sampleRate: sampleRate); if (AmpObj.GetType() == typeof(NoAmpManager)) ((NoAmpManager)AmpObj).Foo(); else ((USBampManager)AmpObj).Bar();