英文:
Accessing private method of another class using Func<Task<T>>
问题
我有两个类,我正在尝试从另一个类中调用另一个类的私有方法。
Program.cs
namespace TestIdentity
{
internal class Program
{
private static int y = 10;
static void Main(string[] args)
{
Func<Task<int>> getter = async () => await Get();
Test test = new Test();
test.SolveAsync(getter).Wait();
}
private static async Task<int> Get()
{
Console.WriteLine("Private value y : " + y);
await Task.Delay(1000);
return 1;
}
}
}
Test.cs
namespace TestIdentity
{
internal class Test
{
public async Task SolveAsync(Func<Task<int>> func)
{
int x = await func();
Console.WriteLine("hello : " + x);
}
}
}
我想知道Test类中的SolveAsync方法如何访问Program类的私有方法和私有属性。
英文:
I have two classes and I'm trying to call private method of class from another class.
Program.cs
namespace TestIdentity
{
internal class Program
{
private static int y = 10;
static void Main(string[] args)
{
Func<Task<int>> getter = async () => await Get();
Test test = new Test();
test.SolveAsync(getter).Wait();
}
private static async Task<int> Get()
{
Console.WriteLine("Private value y : " + y);
await Task.Delay(1000);
return 1;
}
}
}
Test.cs
namespace TestIdentity
{
internal class Test
{
public async Task SolveAsync(Func<Task<int>> func)
{
int x = await func();
Console.WriteLine("hello : " + x);
}
}
}
I wanted to know how SolveAsync method in Test class can access private method of Program class and its private properties.
答案1
得分: 1
Short answer: Test
类本身无法访问私有函数和字段,但你将它们作为参数传递了。
委托是(类型安全的)指针。而你的 Func<Task<int>> getter
是一个专门的委托。所以你创建了一个指向私有函数 Get
的指针。这个指针作为参数传递给了你的 SolveAsync
函数。
SolveAsync
只是调用给定内存地址上的代码块,而不知道它属于 Program
类。
另一个例子:
class Program
{
static void Main(string[] args)
{
int x = 2;
MyMath.Pow2Override(ref x);
Console.WriteLine($"x = {x}");
}
}
static class MyMath
{
public static void Pow2Override(ref int x)
{
x *= x;
}
}
在这里,我们调用了 Pow2Override
,它可以访问局部变量。甚至 Program
类在 Main
函数之外也无法看到 x
。这仍然有效,因为我们提供了引用(相应的内存地址)。
英文:
Short answer: The Test class cannot see the private functions and fields by itself but you gave the references as parameters.
A delegate is a (typesafe) pointer. And your Func<Task<int>> getter
is a specialized delegate. So you created a pointer to the private function Get
. This pointer is given as a parameter in your SolveAsync
function.
The SolveAsync
just calls the chunk of code located at the given Memory address without knowing that it belongs to Program
class.
Another example:
class Program
{
static void Main(string[] args)
{
int x = 2;
MyMath.Pow2Override(ref x);
Console.WriteLine($"x = {x}");
}
}
static class MyMath
{
public static void Pow2Override(ref int x)
{
x *= x;
}
}
Here we call Pow2Override
which has access to a local variable. Not even the class Program
can see x
outside of the Main
function. This again works because we provided the reference (the correspoding memory address).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论