C#的新手,但在PowerShell方面经验丰富。接管别人的代码。编写已编译的PowerShell模块,并尝试根据返回的数据确定如何创建对象。现在,代码返回一个字符串:
ServerResponse<UCCSiteModel> requestModel = this.MakeRequest("/site/api/", "site", "GET", this.Credentials, queryString);
StringBuilder builder = new StringBuilder();
if (requestModel != null && requestModel.Response != null)
{
builder.AppendLine("SiteID: " + requestModel.Response.SiteID);
builder.AppendLine("Identity: " + requestModel.Response.SiteName);
builder.AppendLine("Site Code: " + requestModel.Response.SiteCode);
builder.AppendLine("Contact Name: " + requestModel.Response.ContactName);
builder.AppendLine("Contact Number: " + requestModel.Response.ContactNumber);
builder.AppendLine("Contact Email Address: " + requestModel.Response.ContactEmailAddress);
builder.AppendLine("Address: " + requestModel.Response.Address);
builder.AppendLine("City: " + requestModel.Response.City);
builder.AppendLine("State: " + requestModel.Response.State);
builder.AppendLine("Post Code: " + requestModel.Response.PostCode);
builder.AppendLine("Time Zone: " + requestModel.Response.Timezone);
builder.AppendLine("Longitude: " + requestModel.Response.longitude);
builder.AppendLine("Latitude: " + requestModel.Response.latitude);
this.WriteResponse(requestModel, builder.ToString());
}
如何从requestModel.Response
创建对象以发送回PowerShell而不是字符串?编写PowerShell时,我通常会使用New-Object PsObject
,然后使用Add-Member
。不知道如何在C#中做到这一点,或者它叫什么(所以我可以搜索)。任何人吗?
答案 0 :(得分:4)
您只需在Add-Member
的{{1}}属性上调用Add()
即可镜像Members
的行为(为了便于访问,我会将属性名称更改为CamelCase在PowerShell中):
PSObject
答案 1 :(得分:2)
在不知道所有细节的情况下,我不能说这是最好的计划,但这就是我要做的。您可以定义一个类然后返回它。因此,您将创建一个新类,如下所示:
public class RequestResponse {
public int SiteID { get; set;}
public string Identity { get; set; }
other fields...
}
接下来,在您发布的代码中,您将创建该对象,然后填充该类的属性。
var response = new RequestResponse();
if (requestModel != null && requestModel.Response != null)
{
response.SiteID = requestModel.Response.SiteID;
response.Identity = requestModel.Response.Identity ;
fill in other fields...
this.WriteResponse(requestModel, response);
}
我希望这能让你开始朝着正确的方向前进。
瓦德