Can you auto-generate code for assigning properties of an object in C#? (Visual Studio)

风格不统一 提交于 2020-05-29 06:57:08

问题


Example: I am working with an API that has definitions for various objects with many properties.

This object has about 40 properties, and I'd like to set them all.

Is there a way to auto-generate the following code from an object?

contact.AddressId = null;
contact.Anniversary = null;
contact.AssistantId = null;
contact.BirthDay = null;
contact.Children = null;
contact.CompanyAddressInfo = null;
contact.CompanyIdentifier = null;
contact.DisablePortalLogin = null;
contact.Email = null;
contact.Emails = null;
contact.ExtensionData = null;
contact.Fax = null;
contact.Faxes = null;
contact.FaxExt = null;
contact.FirstName = null;
contact.Gender = null;
contact.Id = null;
contact.Inactive = null;
contact.LastName = null;
contact.LastUpdated = null;
contact.ManagerId = null;
contact.Married = null;
contact.NickName = null;
contact.PersonalAddress = null;
contact.PersonalAddressFlag = null;
contact.Phone = null;
contact.PhoneExt = null;
contact.Phones = null;
contact.PortalPassword = null;
contact.PortalSecurityLevel = null;
contact.Relationship = null;
contact.School = null;
contact.SID = null;
contact.SignificantOther = null;
contact.SiteName = null;
contact.Title = null;
contact.Type = null;
contact.UnsubscribeFlag = null;
contact.UpdatedBy = null;

The purpose is for visualization and for me to see what I am and am not setting in my code.

Edited to be more specific.


回答1:


Try this

    static void Main(string[] args)
    {
        Contact obj = new Contact();
        var props = obj.GetType().GetProperties();

        foreach (var p in props)
            Console.WriteLine("contact.{0}= null;", p.Name);
        Thread.Sleep(1000);
    }

Then copy paste the console screen or write it to a file instead.




回答2:


Create a Visual Studio Snippet with replacements:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0"
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <Header>
    </Header>
    <Snippet>
        <Declarations>
            <Literal>
                 <ID>AddressId</ID>
                 <ToolTip>Enter Address</ToolTip>
                 <Default>Address</Default>
            </Literal>
            <Literal>
                 <ID>Anniversary</ID>
                 <ToolTip>Enter Anniversary</ToolTip>
                 <Default>Anniversary</Default>
            </Literal>
        </Declarations>
        <Code Language="CSharp">
        <![CDATA[contact.AddressId = $AddressId$;
             contact.Anniversary = $Anniversary$;]]></Code>
    </Snippet>
</CodeSnippet>



回答3:


It's been years old but I am posting this since I stumbled upon it and currently there's a solution. If you are using ReSharper, you can use the object's initializer.

var contact = new Contact()
{

};

While inside the brackets of the initializer, you'll get the Resharper's "light bulb". Clicking on it, you are offered the option to "Initialize members". You'll get all properties initialized to their type's default value and you can go on from there, changing those you want. You can even select all of them and extract them into simple assignment statements if the initializer doen't fit your needs




回答4:


Not what you actually want but instead of repeating contact.Property1, contact.Property2 you can use object initializer:

var contact = new Contact
{
    AddressId = foo1,
    Anniversary = foo2,
    AssistantId = foo3,
    BirthDay = foo4,
    Children = foo5,
    CompanyAddressInfo = foo6,

    // ... others fields
}



回答5:


So using Jonathan's answer I've created a method that accepts an object and a name, and spits out all properties with null as a placeholder, as shown in the question:

    static void Main(string[] args)
    {
        ObjectGenerateNullValues(new Contact(), "contact");
    }

    private static void ObjectGenerateNullValues(object objectType, string objectName)
    {
        var props = objectType.GetType().GetProperties();

        using (StreamWriter sw = new StreamWriter(@"c:\temp\ObjectPropertiesOutput.txt", true))
        {
            foreach (var p in props)
            {
                sw.WriteLine("{0}.{1} = null", objectName, p.Name);
            }
        }
    }

I suppose I shall write a little lightweight GUI to do this for me as I continue to explore these APIs.



来源:https://stackoverflow.com/questions/32636955/can-you-auto-generate-code-for-assigning-properties-of-an-object-in-c-visual

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!