简体   繁体   English

访问来自不同命名空间中的不同类的变量

[英]Access a variable from different classes that are in different namespaces

I have a MVVM application, and I need to declare a variable somewhere and access it from everywhere in my assembly, that is, from different classes in different namespaces.我有一个 MVVM 应用程序,我需要在某处声明一个变量并从我的程序集中的任何地方访问它,即从不同命名空间中的不同类。 I have tried to declare an internal variable in the main class but it does not work.我试图在主类中声明一个内部变量,但它不起作用。 Any ideas?有任何想法吗?

Sounds like you want a simple "Service"听起来你想要一个简单的“服务”

namespace en.my.services
{
     public class VariableService
     {
         public string SomeVariable {get; set;}
     }
}

Which you can inject where needed:您可以在需要的地方注入:

using en.my.services; // Make Service namespace known

namespace en.my.clients 
{
    public class MyServiceClient
    {
        VariableService svc = null;

        public MyServiceClient ( VariableService varsserv ) // <- Parameter-Injection via 
                                                            // your DI Framework
        {   
            svc = varserv;
        }

        public void SomeMethod()
        {
            svc.SomeVariable = "Update";
        }
    }
}

I'd recommend to also use an interface.我建议也使用接口。 So you can easily (unit-)test by mocking the interface.因此,您可以通过模拟界面轻松(单元)测试。 So, you'd have IVariableService and VariableService implementing it.所以,你有IVariableServiceVariableService实现它。 The clients would take the interface and your DI Framework config would make the connection from the interface to a singleton instance of the implementation.客户端将采用接口,而您的 DI 框架配置将建立从接口到实现的单例实例的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM