Unity之 C#接口的显示实现的应用1--实现方法的访问权限的自定义

QFramework框架设计中的接口使用技巧(接口+静态拓展)

using UnityEngine;
namespace FrameworkDesign.Example
{
    #region 规则定义
    
    //提供具体方法的全功能类
    public class CanDoEverything
    {
        public void DoSomething1()
        {
            Debug.Log("DoSomething1");
        }
        public void DoSomething2()
        {
            Debug.Log("DoSomething2");
        }
        public void DoSomething3()
        {
            Debug.Log("DoSomething3");
        }
    }
    
    // 该Interface定义了一个可以获取全功能类实例的属性
    public interface IHasEverything
    {
        CanDoEverything CanDoEverything { get; }
    }


    #region 第一套规则 可访问全功能类中的DoSomething1方法(具体类通过继承该接口并显式实现IHasEverything中的CanDoEverything属性)
    public interface ICanDoSomething1 : IHasEverything
    {
    }
    public static class ICanDoSomething1Extension
    {
        public static void DoSomething1(this ICanDoSomething1 self)
        {
            self.CanDoEverything.DoSomething1();
        }
    }
    #endregion


    #region 第二套规则 可访问全功能类中的DoSomething2方法(具体类通过继承该接口并显式实现IHasEverything中的CanDoEverything属性)
    public interface ICanDoSomething2 : IHasEverything
    {
    }
    public static class ICanDoSomething2Extension
    {
        public static void DoSomething2(this ICanDoSomething2 self)
        {
            self.CanDoEverything.DoSomething2();
        }
    }
    #endregion


    #region 第三套规则 可访问全功能类中的DoSomething2方法(具体类通过继承该接口并显式实现IHasEverything中的CanDoEverything属性)
    public interface ICanDoSomething3 : IHasEverything
    {
    }
    public static class ICanDoSomething3Extension
    {
        public static void DoSomething3(this ICanDoSomething3 self)
        {
            self.CanDoEverything.DoSomething3();
        }
    }
    #endregion
    #endregion

    public class InterfaceRuleExample : MonoBehaviour
    {
        #region 使用规则


        public class OnlyCanDo1 : ICanDoSomething1
        {
            //这里需要使用接口显式实现不能让具体实例获取该属性,因为获取到该属性就可以访问所有方法
            CanDoEverything IHasEverything.CanDoEverything { get; } = new CanDoEverything();
        }


        public class OnlyCanDo23 : ICanDoSomething2, ICanDoSomething3
        {
            //这里需要使用接口的显式实现不让具体实例获取该属性,因为获取到该属性就可以访问所有方法
            CanDoEverything IHasEverything.CanDoEverything { get; } = new CanDoEverything();
        }


        #endregion

        private void Start()
        {
            
            OnlyCanDo1 do1 = new OnlyCanDo1();
            do1.DoSomething1();//拓展方法定义

            OnlyCanDo23 do23 = new OnlyCanDo23();
            do23.DoSomething2();//拓展方法定义
            do23.DoSomething3();//拓展方法定义
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值