简体   繁体   English

在C#项目中存储不变变量的好方法是什么?

[英]What's a good way to store unchanging variables in a C# project?

I'm just learning C#, so pardon my n00bness, please. 我只是在学习C#,请原谅我的n00bness。

  • We use Visual Studio 2012 to put together a C#/Selenium project for automated testing. 我们使用Visual Studio 2012将C#/ Selenium项目组合在一起进行自动化测试。
  • We have three credit card processors. 我们有三个信用卡处理器。

I want to store the login credentials, test settings, and test payment items for each processor. 我想存储每个处理器的登录凭据,测试设置和测试付款项目。 I could do this in Python in a minute, using a dict: 我可以在一分钟内使用dict在Python中完成此操作:

processorCreds = {
    'ProcOne': {
        'website': '[url]',
        'username': '[username]',
        'password': '[password]'
    },
    'ProcTwo': {
        'website': '[url]',
        'username': '[username]',
        'password': '[password]'
    },
}

And then I'd just call it when I need it: 然后我会在需要时调用它:

def openProcessor(procName):
    urllib2.urlopen(processorCreds[procName]['website'])

openProcessor('ProcTwo')

I want this in C#, basically. 基本上我想在C#中使用它。 I will only rarely need to change these credentials, and they'll be used in multiple test cases, so I want to be able to pull the information wherever I need it. 我很少需要更改这些凭据,它们将在多个测试用例中使用,因此我希望能够在任何需要的地方提取信息。

What would be the best way for me to put this together? 对我来说,最好的方法是什么? Should I use an XML file, or can this be in a class, or...? 我应该使用XML文件,还是可以在一个类中,或者......?

[EDIT] The alternative I see is that we set the variables each time we have a test case, which doesn't seem... object-oriented. [编辑]我看到的替代方法是,每当我们有一个测试用例时就设置变量,这似乎不是面向对象的。 Or, I suppose I could put the variables on the [Processor]Portal.cs pages... I was just hoping for a way to put alla this in one place with a minimum of fuss, for our occasional "this works for every processor" tests. 或者,我想我可以将变量放在[Processor] Portal.cs页面上......我只是希望能够将这个变量放在一个地方而不用大惊小怪,因为偶尔会出现“这适用于每个处理器测试。

(Also this is totally test data, and would be accessible to the same folk who can already see it now, so I'm not worried.) (这也完全是测试数据,现在已经可以看到它的同一个人可以访问,因此我并不担心。)

.NET offers many ways of storing constant or nearly constant data: you have a choice among multiple ways of reading XML files, configuration files, resource files with your own format, and so on. .NET提供了许多存储常量或接近常量数据的方法:您可以选择多种方式读取XML文件,配置文件,使用您自己的格式的资源文件等等。 If you would like to define a structure like yours in code, you can use IDictionary : 如果您想在代码中定义类似于您的结构,可以使用IDictionary

internal static readonly IDictionary<string,dynamic> ProcessorCreds =
    new Dictionary<string,dynamic> {
        {"ProcOne", new {
            Website = "[url]",
            Username = "[username]",
            Password = "[password]"
        },
        {"ProcTwo", new {
            Website = "[url]",
            Username = "[username]",
            Password = "[password]"
        }
    };

This creates an instance of Dictionary that maps string objects to anonymous objects with three properties - Website , Username , and Password . 这将创建一个Dictionary实例,它将string对象映射到具有三个属性的匿名对象 - WebsiteUsernamePassword Since objects that go in belong to an anonymous class (note the lack of class name between new and the opening curly brace) the value type of the dictionary is defined as dynamic . 由于进入的对象属于匿名类(注意new和大括号之间缺少类名),因此字典的值类型被定义为dynamic This would let you add more attributes in the future without changing anything else. 这样一来,您将来便可以添加更多属性,而无需进行其他任何更改。

You can use ProcessorCreds like this: 你可以像这样使用ProcessorCreds

urlopen(ProcessorCreds[procName].Website);

You can put them in App.Config( Web.Config) in the appsettings section and use the configurationmanager to get he values as shown in the example below 您可以将它们放在appsettings部分的App.Config(Web.Config)中,并使用配置管理器获取其值,如下面的示例所示

<appSettings>
    <add key="username" value="me" />
    <add key="password" value="getmein" />
</appSettings>

In the code you will have the following 在代码中,您将拥有以下内容

string username=ConfigurationManager.AppSettings["username"];

There are a lot of different ways to do this. 有很多不同的方法可以做到这一点。 You could store the data in a static readonly dictionary. 您可以将数据存储在静态只读字典中。

public static readonly Dictionary<int, int> MY_DICTIONARY;

And place this inside a static class available throughout your project. 并将其放在整个项目中可用的静态类中。

You could also store data in the Properties settings.settings file. 您也可以将数据存储在Properties settings.settings文件中。

Generally, in my C# code I try to avoid global data and instead pass information when it is needed. 通常,在我的C#代码中,我尝试避免全局数据,而是在需要时传递信息。 This allows for code that is more easily tested. 这允许更容易测试的代码。

Using C# or Python does not change the answer to this question substantially. 使用C#或Python并没有大大改变这个问题的答案。 If using a mutable in-memory data structure like a dictionary did the trick fine for you in Python, then you can just do the same in C#. 如果在Python中使用像字典这样的可变内存数据结构,那么你可以在C#中做同样的事情。

A similar answer uses dynamic, but it is more idiomatic and there are many advantages in C# to favor using static typing, like so: 类似的答案使用动态,但它更惯用,C#有许多优点,有利于使用静态类型,如下所示:

public class Processor {
    public Uri Website { get; private set; }
    public string Username { get; private set; }
    public string Password { get; private set; }
    public Processor(Uri website, string username, string password) {
        Website = website;
        Username = username;
        Password = password;
    }
}

var processorCreds = new Dictionary<string, Processor> {
    { "ProcOne", new Processor(new Uri("[url]"), "[username]", "[password]") },
    { "ProcTwo", new Processor {new Uri("[url]"), "[username]", "[password]") }
};

which case be used as 哪种情况可以用作

processorCreds["ProcOne"].Website

Your question has more security and procedural implications than technical. 您的问题比技术问题具有更多的安全性和程序含义。

Since you're saving usernames and passwords for payment processing, there're all kinds of risks to storing these where they are publicly available. 由于您要保存用户名和密码以进行付款处理,因此存在将它们存储在公开位置的各种风险。 Do you need PCI compliance in your business? 您的企业是否需要PCI合规性? Given that this is security information, don't you want to keep them under lock-and-key to some extent? 鉴于这是安全性信息,您是否不想在某种程度上将它们保持在锁钥状态? Perhaps keep them in a database, or encrypted in some way. 也许将它们保存在数据库中,或以某种方式进行加密。

If there's no such issue, your appConfig file is probably the best bet: you can define them in your project, and retrieve them using the ConfigurationManager class. 如果没有这样的问题,您的appConfig文件可能是最好的选择:您可以在项目中定义它们,并使用ConfigurationManager类检索它们。 The will be stored in the XML file that is deployed along with your application. 将会存储在与您的应用程序一起部署的XML文件中。 In plain text. 以纯文本格式。

Put them in a static dynamic variable - this is the most pythonish way to do it, although it's not idiomatic c# 将它们放在静态动态变量中-尽管不是惯用的C#,但这是最Python化的方法

static dynamic processorCreds =new {
    ProcOne= new {
        website= "[url]",
        username= "[username]",
        password= "[password]"
    },
    ProcTwo= new {
        website= "[url]",
        username= "[username]",
        password= "[password]"
    },
}

You can then access it using var s = (string) processorCreds.ProcTwo.website; 然后,您可以使用var s = (string) processorCreds.ProcTwo.website;访问它var s = (string) processorCreds.ProcTwo.website;

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

相关问题 C# 如何安全存储不变的密码? - C# How to securly store an unchanging password? 存储与项目相关的图片的好方法是什么? - What's a good way to store project related pictures? 存储大量数字的好方法是什么? (例如572e6561)在C#中 - What's a good way to store extremely large numbers? (Eg. 572e6561) in C# 在C#中编写批处理脚本的好方法是什么? - What's a good way to write batch scripts in C#? 在C#中,什么是显示可缩放,可平移视频的好方法? - In C#, what's a good way for displaying zoomable, pannable video? 在C#中捕获StackOverflow异常的一般方法是什么? - What's a good general way of catching a StackOverflow exception in C#? 什么是C#中的错误操作符? - What's the false operator in C# good for? 来自C背景,在C#中实现const引用数据表/结构的好方法是什么? - Coming from a C background, what's a good way to implement const reference data tables/structures in C#? 使用受保护对象C#编写单元测试的好方法是什么(使用NMock和NUnit框架) - What's a good way to write Unit tests for code with protected objects C# (using NMock, and NUnit framework) ac #dll将错误返回给调用应用程序的好方法是什么? - What's a good way for a c# dll to return error to the calling application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM