简体   繁体   中英

C# making all the private members declared in a container

I have lots of private data members in my code close to 20 lines is there a way to possibly put all these in a container ; i am doing C# 4.0 in VS 2010 .

private const string sig1 = "SignatureField";
private const string sig2 = "Message";
private const string sig3 = "Enter Label name & its Associated Types";
private const string sig4 = "Label 1";
private const string sig5 = "Label 2";

Do you mean as in a #region?

#region Constants
   const string sig1 = "SignatureField";
   const string sig2 = "Message";
   const string sig3 = "Enter Label name & its Associated Types";
   const string sig4 = "Label 1";
   const string sig5 = "Label 2";
   // etc.
#endregion

This will allow you to do a code fold in VS.

Perhaps place them in an array?

private static final string[] sigs = new[] { "SignatureField", "Message", "Enter Label name & its Associated Types", "Label 1", "Label 2" };

And use them like so:

string value = sigs[0];

使用区域,这是来自Microsoft http://msdn.microsoft.com/zh-cn/library/9a1ybwek(v=vs.71).aspx的官方文章

What exactly do you want to do?

If you only do not want to see them most of the time you cann add

#region 

before and #endregion after the private members. That will give you a small + symbol where you can fold code away.

if you want to have the members in a own class or struct you can write a new one, however you would need properties so that the original class can access it ( maybe use the refactoring settings if you mark the lines and right click on it)

If they are all const settings, maybe you are searching for something like a singleton?

If you want them to be changed by the user, you can put these in the App.config of the project and call them with ConfigurationManager.

Here's a begiiner's explanation: http://blogs.technet.com/b/vanih/archive/2008/01/25/configurationmanager-class-in-c.aspx

I'm not sure if I understood you correctly but maybe you can try do something like this:

public class Signatures
{
    private const string sig1 = "SignatureField";

    public static string Sig1
    {
        get
        {
            return sig1;
        }
    }    
}

Next you can use it in other classes if you want:

class Program
{
    static void Main(string[] args)
    {
        Console.Write(Signatures.Sig1);
        Console.ReadKey();
    }
}

Of course you have to remember use only getter for public properties because of consts privates.

I hope I understood you in good way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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