现代 C# 支持嵌套函数的定义。例如:
public bool Test(params int[] args) {
bool isNumberValid(int i) {
return i > 0;
}
foreach(var n in args) {
if(!isNumberValid(n)) {
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
上面的例子我只是作为一个测试用例场景写的,能不能重构也无所谓。现在的问题是,isNumberValid函数创建了多少次?它是否只创建一次,从而被编译器移到父功能块之外?还是在调用父函数时在运行时重新创建(作用域在父堆栈下)?
我在函数的前面放了什么修饰符都没关系(我尝试过使用public,private甚至protected),但我总是收到一个错误,同样的错误。仅在删除修饰符且函数“ Array()”不包含任何修饰符后,代码才干净。有人可以看一下我的代码并向我解释发生了什么吗,我是c#的新手,还是寻求帮助的新手,所以请原谅我迄今为止犯的所有错误。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
public void Array()//nu se pune in interiorul functiei void Main (), deoarece va forma nesting, si ne va da eroare la compilare.
{
int[] intArray;
intArray = new int[3];//all values will be 3
var doubleArray = new[] { 34.23, 10.2, 23.2 };
//var arrayElement = doubleArray[0];
//doubleArray[1] = 5.55;
for (var i = 0; i < intArray.Length; …Run Code Online (Sandbox Code Playgroud) 这是我想要实现的:
public static void foo()
{
// Local function
int? parseAppliedAmountTernary( decimal? d ) {
d.HasValue ? return Convert.ToInt32( Math.Round(d.Value, 0) ) : return null;
}
// The rest of foo...
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到编译错误。这种语法可能吗?我使用的是 Visual Studio 2019、.NET Framework 4,(当前)相当于 C# 7.3。
注意 - 我只是想弄清楚语法......任何关于代码“可读性”或其他美学的哲学讨论虽然有趣,但都不是重点。:)
代码示例(使用 Roslyn 4.0) https://dotnetfiddle.net/TlDY9c
我在玩我的 intcode 计算机实现(从代码 2019 的出现开始),发现当我实现开关(选择要执行的操作)时,它采用了错误的值。
下面的代码演示了这一点。
InstructionPointer有一个值2,opcode有值6意味着OpcodeJumpIfFalse将被使用。函数Jif()被调用得很好,它返回一个值,在我的例子中它返回0. Jif()还修改了 的值InstructionPointer,将其值更改为9。该InstructionPointer会的被增加0(返回值Jif()),我会想到它的价值是9,但它的价值会回去做2。
InstructionPointer += opcode switch
{
OpcodeAdd => Add(),
OpcodeMultiply => Mul(),
OpcodeInput => Inp(),
OpcodeOutput => Out(),
OpcodeJumpIfTrue => Jit(),
OpcodeJumpIfFalse => Jif(),
OpcodeLessThan => Let(),
OpcodeEquals => Equ(),
OpcodeAdjustRelativeBase => Arb(),
OpcodeHalt => End(),
_ => throw new ArgumentOutOfRangeException()
};
Run Code Online (Sandbox Code Playgroud)
显示相同行为的最小示例:
int …Run Code Online (Sandbox Code Playgroud) 我有一个成员函数需要访问成员数据和“本地”数据:
struct S final
{
int i = 123;
// ... a bunch of legacy code ...
void f()
{
// ... a bunch of legacy code ...
double d = 1.23;
// ... a bunch of legacy code ...
g(d);
// ... a bunch of legacy code ...
}
// ... a bunch of legacy code ...
void g(double& d)
{
i = 456; d = 4.56;
}
};
Run Code Online (Sandbox Code Playgroud)
这当然是有效的......但是,随着更多本地变量被f()传递到g(). 有没有一种“简单”的方法可以避免这种情况?
使用 lambda 是“常规”答案,但这意味着 的代码 …