【问题标题】:Calling a base class constructor in derived class after some code block in derived constructor [duplicate]在派生构造函数中的某些代码块之后调用派生类中的基类构造函数[重复]
【发布时间】:2015-05-28 22:50:18
【问题描述】:
public class bar
{
   public bar(list<int> id, String x, int size, byte[] bytes)
   {
     ...
   }
}

public class Foo: Bar
{
    public Foo(list<int> id, String x, someEnumType y):
     base(id, x, sizeof(someEnumType), y)
    {
        //some functionality
    }
}

正如您在上面的代码中看到的,我需要在调用基类构造函数之前将 someEnumType 转换为字节数组类型。有没有办法做到这一点?比如:

public class Foo: Bar
{
    public Foo(list<int> id, String x, someEnumType y)
    {
        //someEnumType to byte array
        base(...)

    }
} 

【问题讨论】:

    标签: c# .net constructor c#-5.0


    【解决方案1】:

    只需在派生类中创建一个方法并调用它....

    public class bar
    {
       public bar(list<int> id, String x, int size, byte[] bytes)
       {
         ...
       }
    }
    
    public class Foo: Bar
    {
        public Foo(list<int> id, String x, someEnumType y):
         base(id, x, sizeof(someEnumType), Convert(y))
        {
            //some functionality
        }
    
        public static byte[] Convert(SomeEnumType type)
        {
            // do convert
        }
    }
    

    【讨论】:

    • 你是对的..我更新了答案
    猜你喜欢
    • 2016-07-19
    • 2015-08-18
    • 2018-07-21
    • 2018-07-16
    • 1970-01-01
    • 2014-11-17
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多