Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/35.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# 如何从一个集合方法c中设置两个类属性#_C# - Fatal编程技术网

C# 如何从一个集合方法c中设置两个类属性#

C# 如何从一个集合方法c中设置两个类属性#,c#,C#,假设我有一个对象类,表示一个页面,该页面有两个属性strTitle,其中存储原始标题和strurtitle,其中存储URL friendlz标题。 我只想在分配struttle时分配strurtitle,因此我使用了以下代码 public class Page { public strUrlTitle {get; private set;} public strTitle { get { return strTitle; }

假设我有一个对象类,表示一个页面,该页面有两个属性
strTitle
,其中存储原始标题和
strurtitle
,其中存储URL friendlz标题。 我只想在分配
struttle
时分配
strurtitle
,因此我使用了以下代码

public class Page
{
    public strUrlTitle {get; private set;}
    public strTitle {
      get
      {
          return strTitle;
      }
      set
      {
          strTitle = value;
          strUrlTitle = HttpUtility.UrlEncode(value.Replace(" ", "-").Trim());
      }
    }
}
但似乎当我调用set方法并分配
strTitle
值时,set方法再次被调用,我们最终进入无限循环。因此,我的问题是如何从一个get方法分配两个值


谢谢

您需要创建一个支持字段。现在,您的setter和getter调用它们自己,导致无限循环:

private string _title;  
public Title 
{
    get
    {
        return _title;
    }
    set
    {
        _title = value;
        UrlTitle = HttpUtility.UrlEncode(value.Replace(" ", "-").Trim());
    }
}

public UrlTitle { get; private set; }

如果搜索“C#property setter infinite loop”,还可以看到许多其他可能的重复项。

还值得一提的是,当使用速记
集时,在编译过程中会自动创建此类支持字段。在习惯了速记形式之后,我最近遇到了同样的问题,当时我需要一个自定义设置器:)