/*
* 游戏开发(Unity&C#)总结34 - Func委托作为方法参数
* 委托作为方法的参数,解释可以使程序更具有解耦性
*
*
*
* **/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Demo : MonoBehaviour
{
void Start()
{
print("TraditionMethod() = "+ TraditionMethod());
//funcDelegate += DelegateSubMehod;
print("DelegateMehod(DelegateSubMehod) = " + DelegateMehod(DelegateSubMehod));
}
public int TraditionMethod()
{
return TraditionSubMethod("123");
}
/// <summary>
/// 假设这个方法名字修改,调用它的其他地方也需要修改。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public int TraditionSubMethod(string str)
{
int intData = 0;
int.TryParse(str, out intData);
return intData;
}
public int DelegateMehod(Func<string, int> funcDelegate)
{
return funcDelegate("456");
}
/// <summary>
/// 假设这个方法名字修改,调用它的其他地方不需要修改。所以更具有解耦性
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public int DelegateSubMehod(string str)
{
int intData = 0;
int.TryParse(str, out intData);
//200
return intData;
}
}
demo下载
https://gitlab.com/demofile1/uploadfile/-/tree/main