是否允许在构造函数中使用此变体?

goo*_*ate 1 c# constructor c#-4.0

我希望有一个重载的构造函数,我根据是否设置了"isFirstPost"来更改基类的值.如果是第一篇文章,我想要rowkey = 000000.如果它不是第一篇文章,那就把它作为一个数字.

不要认为这是一个Azure问题...但我对C#语言更感兴趣,并使条件参数影响基类的设置.我不知道该怎么做.

public class ForumPost : TableServiceEntity
    {
        public ForumPost(string partitionKey, string rowKey): base(partitionKey, rowKey)
        {
        }
        public ForumPost(ForumThread ParentThread, bool IsFirstPost)
        {
            if (IsFirstPost)
            {
                //call constuctor with special values for base class
                //set baseclass rowkey = 0000000
            }

            else {
             //set baseclass rowkey = 1111111111
              }
         }
}
Run Code Online (Sandbox Code Playgroud)

Jak*_*son 5

这是不可能的,因为必须在当前类的构造函数之前调用基础构造函数.你可以做的是定义一个静态函数,它将正确的id传递给基础构造函数.

public class ForumPost : TableServiceEntity
{
    public ForumPost(ForumThread ParentThread, bool IsFirstPost)
        : base(ParentThread, GetID(IsFirstPost))
    {
    }

    static string GetID(bool IsFirstPost)
    {
        return IsFirstPost ? "00000" : "11111";
    }
}
Run Code Online (Sandbox Code Playgroud)