c# - 在派生构造函数中的某个代码块之后调用派生类中的基类构造函数

标签 c# .net constructor c#-5.0

<分区>

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(...)

    }
} 

最佳答案

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

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
    }
}

关于c# - 在派生构造函数中的某个代码块之后调用派生类中的基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29252747/

相关文章:

c# - 无法删除该对象,因为在 ObjectStateManager #2 中找不到它

.net - 加快 ASP.NET 中的构建时间

java - 为什么有些带参数的构造函数仍然调用this()?好像什么也没做?

c++ - 采用 std::initializer_list 的构造函数优于其他构造函数

c# - 我的通用解耦非常丑陋

c# - Identity Server 4 OpenID Connect Discovery 是否应该公开?

c# - .net large for 循环变慢

c++ - 在 C++ 中调用父类的构造函数之前在类中初始化变量

c# - 覆盖抽象方法,但保持方法抽象?

C#——我们应该在 Indexer Method 中转换为 get