I'm trying to build a class that will optionally direct my trapped error conditions by writing a message to a TextBox (the reference to which is specified by the main program) and or throwing an exception.
The logic to write to the text box and/or throw an error is specified in the main program by setting the value of class member int ThrowWhen
to a member of enum WhenToThrow
. Here is the class:
public static class DoExceptions
{
public static Windows.UI.Xaml.Controls.TextBox ExceptionTextBox;
public static int ThrowWhen;
public enum WhenToThrow { throw_null, throw_never, throw_always, throw_if_no_output };
private static int throwWhen;
public static int ThrowWhen
{
get
{
return throwWhen;
}
set
{
throwWhen = value;
}
}
public static void Action(string msg)
{
if (ExceptionTextBox != null)
{
ExceptionTextBox.Text = msg;
if ((int) ThrowWhen == (int)WhenToThrow.throw_always)
{
throw new Exception(msg);
}
}
else
{
if ((int)ThrowWhen == (int)WhenToThrow.throw_if_no_output)
{
throw new Exception(msg);
}
}
}
}
The above class is defined in a namespace called MobileDAQ. (Everything else defined in that namespace is working.)
In my main program (which is a Windows Universal Blank App targeting Windows 8.1), I am trying to set the parameter ThrowWhen as follows:
MobileDAQ.DoExceptions.ThrowWhen = MobileDAQ.DoExceptions.throw_always;
But both the left and right sides of the assignment throw the same error: "Error CS0103 The name 'MobileDAQ.DoExceptions.ThrowWhen' does not exist in the current context."
, or ... MobileDAQ.DoExceptions.throw_always ...
.
I must be making a stupid mistake (or else there's a serious caveat about static classes that thee doco doesn't give enough attention to), but everything I try either makes no difference or throws a new compile error.
Where am I going wrong?
throw_always
is a member of WhenToThrow
enum. It's not member of DoExceptions
class. You missed the enum name:
MobileDAQ.DoExceptions.ThrowWhen = MobileDAQ.DoExceptions.WhenToThrow.throw_always;
^
Also I suggest you to use using
directive to allow use types in MobileDAQ
namespace:
using MobileDAQ;
...
DoExceptions.ThrowWhen = DoExceptions.WhenToThrow.throw_always;
Or even with new C# 6 feature you can allow access static members:
using static MobileDAQ.DoExceptions;
...
ThrowWhen = WhenToThrow.throw_always;
I got it! I was trying to do the assignment to ThrowWhen
from within the class declarations section of the program. I moved it to the Grid_Loaded
event routine and everything was fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.