0

我正在尝试从另一个对象的基本接口创建一个新对象。

IDailyEventBasecurrentEvent的基础接口,也是DailyEventEntity的基础接口。

有没有办法从currentEvent对象创建新的DailyEventEntity对象,而无需再次重新分配所有共享的基本属性值?

private bool CreateDailyEvent(EventDefinitionEntity eventApp
        ,IDailyEventBase currentEvent)
    {
        //create daily event
        DailyEventEntity dailyEvent = iDailyEvent as DailyEventEntity;
4

3 回答 3

0

currentEvent implementing IDailyEventBase interface, but you can't assign it to DailyEventEntity class until it not the same type or type derived from DailyEventEntity.

And I'm not recommending you to do this actions inside CreateDailyEvent method because somebody can create class that implements IDailyEventBase and pass object of this class to your your method what will get you InvalidCastException in runtime.

于 2013-06-26T19:45:12.347 回答
0

听起来您想保留一个现有对象(某种类型的,实现一个接口)并将其包装(“装饰”)到另一个实现其他一些附加接口的对象中。这可以通过“聚合”现有对象并将该接口的所有方法委托给内部对象来实现。

这是类如何将实现委托给现有对象的示例:

interface IDailyEventBase 
{
    void MethodOne();
}

class SomeEvent : IDailyEventBase ...

class DailyEventEntity : IDailyEventBase 
{
   IDailyEventBase inner;
   public DailyEventEntity(IDailyEventBase inner)
   {
       this.inner = inner;
   }

   public void MethodOne() 
   {
      // delegate directly to wrapped class. You can also add more code here.
      return inner.MethodOne();
   }

   // other methods of this class (may use properties of "inner" too)
   public void OtherMethod()...
}

和使用示例:

IDailyEventBase other = new SomeEvent();
var delegatingDailyEvent = new DailyEventEntity(other);
于 2013-06-26T20:00:41.930 回答
0

您不能从接口创建对象。

话虽如此,您可以使用反射来实例化对象的基类的对象。

像这样的东西:

var o = Activator.CreateObject(this.GetType().BaseType);
于 2013-06-26T19:39:10.287 回答