How can I store a Type in a static field, so that I can do something like this (note: just an example, in pseudocode)?:
public class Logger
{
public static Type Writer;
public static void SetWriter(Type @new)
{
Writer = @new;
}
public static void Write(string str)
{
Writer.Write(str);
}
}
Very simple:
Type variableName = typeof(SomeTypeName);
or
Type variableName = someObject.GetType();
Not sure this will help with what you actually want to do, though. See the other answers.
Except for the fact that new
is a keyword, your code to store the type should work fine.
However, your code
Writer.Write(str);
is meaningless.
The class Type
does not have a method Write(string)
.
It feels like what you are after is an interface
public interface IWriter
{
public Write(string text);
}
public class Logger
{
public static IWriter Writer;
public static void SetWriter(IWriter newWriter)
{
Writer = newWriter;
}
public static void Write(string str)
{
Writer.Write(str);
}
}
That way, you would pass any class that implements IWriter
into SetWriter
, e.g.
public class MyWriter : IWriter
{
public void Write(string text)
{
// Do something to "write" text
}
}
Logger.SetWriter(new MyWriter());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With