//=======================================================
using UnityEngine;
public class CanDoEveryThing
{
public void DoSomething1()//==>4
{
Debug.Log("DoSomething1");
}
public void DoSomething2()
{
Debug.Log("DoSomething2");
}
public void DoSomething3()
{
Debug.Log("DoSomething3");
}
}
//=======================================================
public interface IHasEveryThing
{
CanDoEveryThing CanDoEveryThing { get; }
}
//=======================================================
public interface ICanDoSomething1 : IHasEveryThing
{
}
public static class ICanDoSomeThing1Extensions
{//静态拓展类
//DoSomething1扩展方法只能应用于实现了ICanDoSomething1接口的对象上。
//这意味着只有当一个对象(或变量类型)实现了这个接口,
//IDE才会识别并提供该扩展方法的自动完成提示,且在编译时期绑定到正确的方法实现上。
public static void DoSomething1(this ICanDoSomething1 self)
{
//this ICanDoSomething1 self整体表示在ICanDoSomeThing1Extensions静态类中的扩展方法里,
//DoSomething1方法的调用者必须是一个实现了ICanDoSomething1接口的对象,
//而self就是对该对象的引用,通过它可以在扩展方法内部访问到对象的成员和实现的功能。
self.CanDoEveryThing.DoSomething1();
}
}
//=======================================================
public interface ICanDoSomething2 : IHasEveryThing
{
}
public static class ICanDoSomeThing2Extensions//静态拓展类
{
public static void DoSomething2(this ICanDoSomething2 self)
{
self.CanDoEveryThing.DoSomething2();
}
}
//=======================================================
public interface ICanDoSomething3 : IHasEveryThing
{
}
public static class ICanDoSomeThing3Extensions//静态拓展类
{
public static void DoSomething3(this ICanDoSomething3 self)
{
self.CanDoEveryThing.DoSomething3();
}
}
//=======================================================
public class InterfaceRuleExample : MonoBehaviour
{
public class OnlyCanDo1 : ICanDoSomething1//只实现了ICanDoSomething1接口
{
CanDoEveryThing IHasEveryThing.CanDoEveryThing { get; } = new CanDoEveryThing();
}
public class OnlyCanDo23 : ICanDoSomething2, ICanDoSomething3//只实现了ICanDoSomething2和ICanDoSomething3接口
{
CanDoEveryThing IHasEveryThing.CanDoEveryThing { get; } = new CanDoEveryThing();
}
private void Start()
{
var onlyCanDo1 = new OnlyCanDo1();
// 可以调用 DoSomething1
onlyCanDo1.DoSomething1();
//拓展方法的DoSomething1()
//对OnlyCanDo1的实例onlyCanDo1调用DoSomething1()时,流程如下:
//查找实例方法:编译器首先检查OnlyCanDo1类是否直接定义了DoSomething1方法,发现没有。
//考虑接口实现:然后注意到OnlyCanDo1实现了ICanDoSomething1接口,但该接口同样没有直接定义DoSomething1的实现。
//搜索扩展方法:编译器接下来在已引入的命名空间中查找是否有针对ICanDoSomething1接口(或其基类、接口)的扩展方法。
//这时,它找到了ICanDoSomeThing1Extensions静态类中定义的静态扩展方法public static void DoSomething1(this ICanDoSomething1 self)。
//匹配与绑定:由于OnlyCanDo1实现了ICanDoSomething1,这个扩展方法的首个参数this ICanDoSomething1 self与onlyCanDo1实例匹配,
//因此编译器成功绑定并使用这个扩展方法。
// 不能调用 DoSomething2 和 3 会报编译错误
// onlyCanDo1.DoSomething2();
// onlyCanDo1.DoSomething3();
var onlyCanDo23 = new OnlyCanDo23();
// 不可以调用 DoSomething1 会报编译错误
// onlyCanDo23.DoSomething1();
// 可以调用 DoSomething2 和 3
onlyCanDo23.DoSomething2();
onlyCanDo23.DoSomething3();
}
}
C#接口 + 扩展时用于限制方法的访问规则(静态拓展)
于 2024-05-09 13:34:39 首次发布