存储对实例方法的静态引用?
我想创建一个包含委托的静态数组。我将使用这个数组来查找我需要的委托。例如:
class HandlerID
{
public int ID { get; set; }
public Func<int, bool> Handler { get; set; }
}
protected const HandlerID[] HandlerIDs = {
new SectionRenderer() { ID = SectionTypes.Type1, Handler = MyType1Handler },
new SectionRenderer() { ID = SectionTypes.Type2, Handler = MyType2Handler },
// Etc.
}
protected bool MyType1Handler(int arg)
{
return false;
}
// Etc.
但是,对 HandlerID
数组中的 Handler
进行赋值会出现以下错误:
非静态字段、方法或属性“MyType1Handler(int)”需要对象引用
我希望该数组是 const,因此不必为每个实例进行初始化我的班级。有没有办法将实例方法存储在静态数组中?
I'd like to create a static array that contains delegates. I will use this array to look up the delegate that I need. For example:
class HandlerID
{
public int ID { get; set; }
public Func<int, bool> Handler { get; set; }
}
protected const HandlerID[] HandlerIDs = {
new SectionRenderer() { ID = SectionTypes.Type1, Handler = MyType1Handler },
new SectionRenderer() { ID = SectionTypes.Type2, Handler = MyType2Handler },
// Etc.
}
protected bool MyType1Handler(int arg)
{
return false;
}
// Etc.
However, the assignments to Handler
in the HandlerID
array gives the following error:
An object reference is required for the non-static field, method, or property 'MyType1Handler(int)'
I'd prefer the array is const
so it doesn't have to be initialized for every instance of my class. Is there any way to store an instance method in a static array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这没有道理。
当您调用数组中的委托时,它们需要您的类的实例来进行操作。
因此,您需要为每个类实例提供一组单独的委托。
如果这些方法实际上不需要实例来操作,您可以将它们设置为
静态
,这将解决问题。或者,您可以将实例作为委托的参数,并使用调用该方法的 lambda 表达式:Handler = (instance, arg) =>实例.MyType1Handler(arg)
That doesn't make sense.
When you call the delegates in the array, they need an instance of your class to operate on.
Therefore, you need a separate set of delegates for each class instance.
If the methods don't actually need an instance to operate on, you can make them
static
, which will fix the problem.Alternatively, you can take the instance as a parameter to the delegate, and use a lambda expression that calls the method:
Handler = (instance, arg) => instance.MyType1Handler(arg)
您不能在 C# 中声明 const 数组,请尝试 readonly ,它可以确保指向数组(实例)的指针不会更改,但据我所知,没有办法以声明方式阻止元素被更改。
You cannot declare a
const
array in C#, tryreadonly
which ensures the pointer to the array (the instance) will not change but as far as I know there is no way to declaratively prevent the elements from being changed.您无法创建静态函数的委托,也无法创建不存在的对象实例中函数的委托。但是,您可以存储 MethodInfo 并稍后在实例上调用它。
You can't create a delegate to a static function and you can't create a delegate to a function in an non existent object instance. However you can store the MethodInfo and at a later time invoke that on an instance.