【问题标题】:How to configure the return string based on user input?如何根据用户输入配置返回字符串?
【发布时间】:2020-07-27 16:38:55
【问题描述】:

我有一个场景,我应该向现有代码添加一个特性,这个特性应该从用户那里获取输入并形成一个字符串。现在默认情况下,代码附带 full name = firstnamelastname。但我应该根据用户需求使其可配置,用户可以添加任何属性,如位置或电话号码以显示全名。例如,格式可以是 [firstname + lastname + location or lastname + firstname + phonenumber]

我已经设法获取用户输入并将其存储在一个名为 test 的变量中,这是它的代码。

[DataMember]
        public string FullName
        {
            get
            {
                string test = "";
                test = Services.GetService<IGlobalOptionsBrokerDataAccess>().test1();
                return string.Format("{0} {1} {2}", this.FirstName, this.MiddleName, this.LastName);
            }
            set
            {
                _fullName = value;
            }
        }

那么我怎样才能让它动态工作呢?这里是值如何在 test 变量中可用的屏幕截图。如果用户想要拥有 ManagerID,那么我怎样才能让它动态工作呢?

还有什么我应该提供的,以便你们在那里更容易吗?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    可能不是最佳解决方案,但这是我很快想到的。使您的格式字符串动态化可以帮助您。

    var posDict = new Dictionary<string, string> {
        {"FirstName","{0}" },
        {"MiddleName","{1}" },
        {"LastName","{2}" }};
    
    var test = "FirstName,LastName,MiddleName";
    var posString = "";
    foreach (var prop in test.Split(','))
        posString += $"{posDict.First(x => x.Key == prop).Value} ";
    
    return string.Format(posString, this.FirstName, this.MiddleName, this.LastName);
    

    【讨论】:

      【解决方案2】:

      我找到了比上面提到的更好的解决方案。

       string[] columnNames = format.Split(new char[] { ',' });
                  string userFullNameAsPerFormat = string.Empty;
                  string defaultFullName = this.FirstName + " " + this.LastName;
      
              // Get the Type object corresponding to MyClass.
              Type myType = typeof(Courion.BusinessServices.Access.ProfileDTO);
                          // Get the PropertyInfo object by passing the property name.
                          PropertyInfo myPropInfo = myType.GetProperty(item.Trim());
          userFullNameAsPerFormat += (string) myPropInfo.GetValue(this) + " ";
      

      【讨论】:

        猜你喜欢
        • 2016-01-25
        • 2017-01-11
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多