Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 修剪对象方法中的所有字符串属性时发生异常-只能对Type.IsGenericParameter为true的类型调用该方法_C#_C# 4.0 - Fatal编程技术网

C# 修剪对象方法中的所有字符串属性时发生异常-只能对Type.IsGenericParameter为true的类型调用该方法

C# 修剪对象方法中的所有字符串属性时发生异常-只能对Type.IsGenericParameter为true的类型调用该方法,c#,c#-4.0,C#,C# 4.0,下面是我遇到错误的代码:“只能对Type.IsGenericParameter为true的类型调用方法。” 我无法修剪对象中的所有字符串属性。您显示的代码执行foreach循环零次,因为您的属性是非公共的 如果您解决了这个问题,您将得到一个null引用异常,因为您从属性getter读取了null字符串,然后在null上调用Trim() 您提供的代码似乎没有比这些问题更多的问题。如果您需要有关其他代码的帮助,请更新您的问题。您提供的代码没有说明问题。(我刚刚将其放入控制台应用程序中,效果很好。)嗨

下面是我遇到错误的代码:“只能对Type.IsGenericParameter为true的类型调用方法。”


我无法修剪对象中的所有字符串属性。

您显示的代码执行
foreach
循环零次,因为您的属性是非公共的

如果您解决了这个问题,您将得到一个
null
引用异常,因为您从属性getter读取了
null
字符串,然后在
null
上调用
Trim()


您提供的代码似乎没有比这些问题更多的问题。如果您需要有关其他代码的帮助,请更新您的问题。

您提供的代码没有说明问题。(我刚刚将其放入控制台应用程序中,效果很好。)嗨,Jon,我执行了这段代码,但它没有返回字符串的属性信息&我检查了obj。GetType()向我抛出了错误。请显示完整的堆栈跟踪。@user2752023:我怀疑您在不同的项目中执行了类似的代码。正如我所说,您给出的确切代码很好。这是一个简单的单页windows窗体应用程序,我得到-[System.InvalidOperationException]{“方法只能在Type.IsGenericParameter为true的类型上调用。”}System.InvalidOperationException。我是一个新手,但我不确定从您的角度来看这是如何工作的。
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CustomInfo obj = new CustomInfo();
        var stringProperties = obj.GetType().GetProperties()
                      .Where(p => p.PropertyType == typeof(string));

        foreach (var stringProperty in stringProperties)
        {
            string currentValue = (string)stringProperty.GetValue(obj, null);
            stringProperty.SetValue(obj, currentValue.Trim(), null);
        }
    }

}

public class CustomInfo
{
    int UserId { get; set; }
    string UserName { get; set; }
    string Country { get; set; }
    string City { get; set; }
    DateTime DOB { get; set; }
    bool isActiveUser { get; set; }

}