您可以自动生成用于在C#中分配对象属性的代码吗? (视觉工作室) [英] Can you auto-generate code for assigning properties of an object in C#? (Visual Studio)

查看:99
本文介绍了您可以自动生成用于在C#中分配对象属性的代码吗? (视觉工作室)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:我正在使用一个API,该API定义了具有许多属性的各种对象.

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

该对象大约有40个属性,我想全部设置它们.

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.

编辑后更加具体.

推荐答案

因此,使用 Jonathan的答案,我创建了一个接受对象和名称的方法,并使用null作为占位符吐出所有属性,如问题所示:

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);
            }
        }
    }

我想在继续探索这些API时,我将为我编写一个轻量级的GUI.

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

这篇关于您可以自动生成用于在C#中分配对象属性的代码吗? (视觉工作室)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆