存储类型字段/变量

Jwo*_*sty 8 c# static field

如何在静态字段中存储Type,以便我可以执行类似的操作(注意:只是一个示例,在伪代码中)?:

public class Logger
{
    public static Type Writer;

    public static void SetWriter(Type @new)
    {
        Writer = @new;
    }

    public static void Write(string str)
    {
        Writer.Write(str);
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*per 20

非常简单:

Type variableName = typeof(SomeTypeName);
Run Code Online (Sandbox Code Playgroud)

要么

Type variableName = someObject.GetType();
Run Code Online (Sandbox Code Playgroud)

但不确定这会对你真正想做的事情有所帮助.看到其他答案.


Eri*_* J. 3

除了它是一个关键字之外new,存储类型的代码应该可以正常工作。

但是,你的代码

Writer.Write(str);
Run Code Online (Sandbox Code Playgroud)

毫无意义。

该类Type没有方法Write(string)

感觉你追求的是一个界面

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您就可以将实现的任何类传递给IWriterSetWriter例如

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

Logger.SetWriter(new MyWriter());
Run Code Online (Sandbox Code Playgroud)