亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更改對象中每個字符串屬性的值

更改對象中每個字符串屬性的值

C#
LEATH 2022-06-12 10:34:55
我有一個包含許多子對象的對象,每個子對象都有不同數量的字符串屬性。我想編寫一個方法,允許我輸入一個父對象,該對象將遍歷每個子對象中的每個字符串屬性,并從屬性內容中修剪空白。對于可視化:public class Parent{    Child1 child1 { get; set;}    Child2 child2 { get; set;}    Child3 child3 { get; set;}}public class Child1 (Child2 and Child3 classes are similar){    string X { get; set; }    string Y { get; set; }    string Z { get; set; }}我有以下代碼,它在父類中創建一個屬性列表,然后遍歷每個屬性并找到字符串的子屬性,然后對它們進行操作。但是由于某種原因,這似乎對屬性的值沒有任何影響。private Parent ReduceWhitespaceAndTrimInstruction(Parent p){    var parentProperties = p.GetType().GetProperties();    foreach(var properties in parentProperties)    {        var stringProperties = p.GetType().GetProperties()            .Where(p => p.PropertyType == typeof(string));        foreach(var stringProperty in stringProperties)        {            string currentValue = (string)stringProperty.GetValue(instruction, null);            stringProperty.SetValue(p, currentValue.ToString().Trim(), null);        }    }    return instruction;}編輯:忘了提。問題似乎來自內部foreach,外部 foreach 查找每個屬性,但查找僅是字符串的屬性似乎無法正常工作。編輯:更新方法private Parent ReduceAndTrim(Parent parent)        {            var parentProperties = parent.GetType().GetProperties();            foreach (var property in parentProperties)            {                var child = property.GetValue(parent);                var stringProperties = child.GetType().GetProperties()                    .Where(x => x.PropertyType == typeof(string));                foreach (var stringProperty in stringProperties)                {                    string currentValue = (string) stringProperty.GetValue(child, null);                    stringProperty.SetValue(child, currentValue.ToString().Trim(), null);                }            }            return parent;        }
查看完整描述

2 回答

?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

您的stringProperties枚舉不包含任何項目,因為您要求Parent類型為您提供類型的所有屬性string- 沒有。


var stringProperties = p.GetType().GetProperties()

    .Where(p => p.PropertyType == typeof(string));

注意p是類型Parent,所以p.GetType()產量typeof(Parent)。


您需要獲取's 實例Child的每個屬性值(每個實例) :Parent


var parentProperties = p.GetType().GetProperties();


foreach (var property in parentProperties)

{    

    var child = property.GetValue(p);

    var stringProperties = child.GetType().GetProperties()

        .Where(p => p.PropertyType == typeof(string));


    // etc

}


查看完整回答
反對 回復 2022-06-12
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

GetProperties 方法僅返回您的類型的公共屬性。如果您將 Parent 類的屬性更改為以下內容,您應該能夠繼續前進:


public class Parent

{

    public Child1 Child1 { get; set; }

    public Child2 Child2 { get; set; }

    public Child3 Child3 { get; set; }

}

但是這行代碼仍然會返回 null,因為您的子類中沒有“父”屬性:


var child = property.GetValue(parent);

我希望它有所幫助:D


查看完整回答
反對 回復 2022-06-12
  • 2 回答
  • 0 關注
  • 182 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號