受保护的构造函数派生类问题

时间:2012-12-19 19:47:36

标签: c# class methods constructor protected

我确信这个问题已被问过很多次了;但是我遇到了问题。所以我创建了一个单独的类;专门用于验证是否存在正确的用户级别。

以下是测试这些权限级别的代码:

    class Elevated_Rights
    {

        // Token Bool:
        private bool _level = false;

        #region Constructor:

        protected Elevated_Rights()
        {

            // Invoke Method On Creation:
            Elevate();

        }

        #endregion

        public void Elevate()
        {

            // Get Identity:
            WindowsIdentity user = WindowsIdentity.GetCurrent();

            // Set Principal
            WindowsPrincipal role = new WindowsPrincipal(user);

            #region Test Operating System for UAC:

            if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
            {

                // False:
                _level = false;

                // Todo: Exception/ Exception Log

            }

            #endregion

            else
            {

                #region Test Identity Not Null:

                if (user == null)
                {

                    // False:
                    _level = false;

                    // Todo: "Exception Log / Exception"

                }

                #endregion

                else
                {

                    #region Ensure Security Role:

                    if (!(role.IsInRole(WindowsBuiltInRole.Administrator)))
                    {

                        // False:
                        _level = false;

                        // Todo: "Exception Log / Exception"

                    }

                    else
                    {

                        // True:
                        _level = true;

                    }

                    #endregion


                } // Nested Else 'Close'

            } // Initial Else 'Close'

        } // End of Class.

    }

因此该部分按预期工作;然而,当我将这个类继承到另一个类来利用受保护的构造函数时,我遇到了障碍。

    class Default_Configuration : Elevated_Rights
    {

        #region Constructor:

        public Default_Configuration() : base()
        {


            Elevate();


        }

        #endregion



    }

但是当我打电话给那个新班级时;该方法声明:“由于构造函数权限导致访问无效”。它理论上应该有效;有什么我想念的吗?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

我认为你的问题出在其他地方:我将这两个类定义粘贴到一个项目中,构建得很好。实例化了一个名为Default_Configuration的新Elevate(),没有错误。

如果您在混合使用publicprotected方法时遇到其他问题,可以使用blog post by Peter Hallam来描述问题。

基本上,您不能从派生类中的protected实例方法调用基类中的public实例方法;这样做会允许“恶意”派生类在基类protected中创建所有public方法,只需为它们编写包装器。

答案 1 :(得分:0)

        new Default_Configuration().Elevate();

这条线适合我。

什么不适合你?