Type of store in field / variable

How to save 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);
    }
}
+5
source share
3 answers

Very simple:

Type variableName = typeof(SomeTypeName);

or

Type variableName = someObject.GetType();

Not sure if this will help with what you really want to do. See Other Answers.

+12
source

Except for being newa keyword, your type storage code should work fine.

However your code

Writer.Write(str);

doesn't make sense.

The class Typehas no method Write(string).

It looks like you are following the 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);
    }
}

Thus, you must pass any class that implements IWriterin SetWriter, for example.

public class MyWriter : IWriter
{
    public void Write(string text)
    {
        // Do something to "write" text
    }
}

Logger.SetWriter(new MyWriter());
+2
source

, , ? , ( , ) System.IO TextWriter, ...

:

public class Logger
{
    public Logger(TextWriter writer)
    {
        _writer = writer;
    }

    private TextWriter _writer;    

    public void Write(string text)
    {
        _writer.Write(text);
    }
}

Now, is it a good idea to make the publication public and rely on the users of your code to make sure it is always valid? Probably not, but that's more of a design consideration. In addition, your java style setter is A) atypical for C #, which has nice syntactic support for properties, and B) is useless since the support field is public.

0
source

All Articles