gpt4 book ai didi

c#-4.0 - 使用委托(delegate)调用私有(private)方法

转载 作者:行者123 更新时间:2023-12-02 01:04:53 24 4
gpt4 key购买 nike

我正在阅读 CLR via C# 第 4 版。在涉及委托(delegate)的章节(第 17 章)中,写道:

The FeedbackToConsole method is defined as private inside the Program type, but the Counter method is able to call Program’s private method. In this case, you might not expect a problem because both Counter and FeedbackToConsole are defined in the same type. However, this code would work just fine even if the Counter method was defined in another type. In short, it is not a security or accessibility violation for one type to have code that calls another type’s private member via a delegate as long as the delegate object is created by code that has ample security/ accessibility.

我正在试验这个想法,但我无法从其他类型调用私有(private)方法。这是我的代码:

namespace DelegatesEvents
{
class Program
{
public static void Main(string[] args)
{
Counter(1, 2, new FeedBack(DelegateEventsDemo.FeedBackToConsole));
Console.ReadLine();
}

private static void Counter(int p1, int p2, FeedBack feedBack)
{
for (int i = p1; i <= p2; i++)
{
if (feedBack != null)
{
feedBack(i);
}
}
}
}
}

namespace DelegatesEvents
{
internal delegate void FeedBack(Int32 val);

public class DelegateEventsDemo
{
private static void FeedBackToConsole(Int32 val)
{
Console.WriteLine("Good morning delegates" + val);
}
}
}

当我将 FeedBackToConsole 声明为私有(private)时,如果我尝试以其他方式调用它,则无法在委托(delegate)中调用它。

我哪里错了?

最佳答案

简而言之,只要委托(delegate)对象是由具有足够安全性/可访问性的代码创建 .

DelegateEventsDemo必须创建委托(delegate)对象。所以我们添加 public GetFeedBackDelegate方法(您也可以添加属性)返回引用私有(private)方法的委托(delegate)对象。

namespace DelegatesEvents
{
internal delegate void FeedBack(Int32 val);

public class DelegateEventsDemo
{
private static void FeedBackToConsole(Int32 val)
{
Console.WriteLine("Good morning delegates" + val);
}

internal static FeedBack GetFeedBackDelegate()
{
return FeedBackToConsole;
}
}
}

并被代码使用:

namespace DelegatesEvents
{
class Program
{
public static void Main(string[] args)
{
Counter(1, 2, DelegateEventsDemo.GetFeedBackDelegate());
Console.ReadLine();
}

private static void Counter(int p1, int p2, FeedBack feedBack)
{
for (int i = p1; i <= p2; i++)
{
if (feedBack != null)
{
feedBack(i);
}
}
}
}
}

关于c#-4.0 - 使用委托(delegate)调用私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23588750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com