如果条件如何解决fieldinfo错误? [英] How to resolve fieldinfo error if condition?
本文介绍了如果条件如何解决fieldinfo错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我写了这段代码但收到错误: -
Hello,
I have write this code but its getting error:-
acceptedCommandsFieldInfo is a field but is used like a type
请帮我解决这个错误。
预付款。
Ankit Agarwal
软件工程师
我尝试过:
Pleas help me how to resolve this error.
Thanks in Advance.
Ankit Agarwal
Software Engineer
What I have tried:
class MyService
{
const int SERVICE_ACCEPT_PRESHUTDOWN = 0x100;
const int SERVICE_CONTROL_PRESHUTDOWN = 0xf;
FieldInfo acceptedCommandsFieldInfo =
typeof(ServiceBase).GetField("acceptedCommands", BindingFlags.Instance | BindingFlags.NonPublic);
if (acceptedCommandsFieldInfo == null)// Error in this line
throw ApplicationException("acceptedCommands field not found");// Error in this line
int value = (int)acceptedCommandsFieldInfo.GetValue(this);// Error in this line
acceptedCommandsFieldInfo.SetValue(this, value SERVICE_ACCEPT_PRESHUTDOWN);// Error in this line
}
推荐答案
问题是您正在类中运行此代码。你不能这样做,你必须在你班上的方法中运行代码。
看起来你想创建一个服务?然后将它放在OnStart
函数中(但是你的类也必须从ServiceBase派生)。同样在最后一行中,传递值SERVICE_ACCEPT_PRESHUTDOWN,它看起来像两个变量。你只能通过一个。我不确切地知道你要做什么,所以你必须知道自己要通过哪一个(但我想它将是SERVICE_ACCEPT_PRESHUTDOWN)。此外,您必须使用抛出新的ApplicationException
而不是抛出ApplicationException
。
The problem is that you are running this code right in the class. You cannot do this, you have to run the code in a method in your class.
It looks like you want to create a service? Then put it in anOnStart
function (but then your class has to derive from ServiceBase, too). Also in your last line, you pass "value SERVICE_ACCEPT_PRESHUTDOWN" which look like two variables. You can only pass one. I don't know exactly what you try to do, so you have to know yourself which one to pass there (but I guess it will be SERVICE_ACCEPT_PRESHUTDOWN). Also, you have to usethrow new ApplicationException
instead ofthrow ApplicationException
.
class MyService : ServiceBase
{
protected override void OnStart(string[] args)
{
FieldInfo acceptedCommandsFieldInfo = typeof(ServiceBase).GetField("acceptedCommands", BindingFlags.Instance | BindingFlags.NonPublic);
if (acceptedCommandsFieldInfo == null)
throw new ApplicationException("acceptedCommands field not found");
int value = (int)acceptedCommandsFieldInfo.GetValue(this);
acceptedCommandsFieldInfo.SetValue(this, SERVICE_ACCEPT_PRESHUTDOWN);
}
}
这篇关于如果条件如何解决fieldinfo错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文