C# BlogEngine.NET上的System.StackOverflowException

C# BlogEngine.NET上的System.StackOverflowException,c#,stack-overflow,C#,Stack Overflow,我正在使用BlogEngine.NET,需要将BlogId设置为特定的Guid(blogIdstr)。我似乎不知道如何从默认的blogId更改它。这是我目前拥有的代码,但它给了我一个StackOverflowException 这两个在基类中 public virtual TKey Id { get; set; } public Guid BlogId { get { return BlogId; <-- Stack Overflow } set

我正在使用BlogEngine.NET,需要将BlogId设置为特定的Guid(blogIdstr)。我似乎不知道如何从默认的blogId更改它。这是我目前拥有的代码,但它给了我一个StackOverflowException

这两个在基类中

public virtual TKey Id { get; set; }

public Guid BlogId 
{ 
get 
   { 
       return BlogId; <-- Stack Overflow
   }

set
   {
       string blogIdstr = "FCA96EFB-D51C-4C41-9F85-3EEB9C50BDE7";
       Guid blogIdGuid = Guid.Empty;
       blogIdGuid = Guid.Parse(blogIdstr);
   }
}

如何设置blogId并避免StackOverflowException?提前感谢。

您的
get
方法正在调用自身,而您的
set
方法本质上是通过设置该方法的本地值来发出no op。如果要在getter和setter内部执行某些操作,则需要为属性提供一个支持字段:

private Guid _blogId;
public Guid BlogId 
{ 
   get 
   { 
       return _blogId;
   }

   set
   {
       //some operation against value here, Validate(value), etc.
       _blogId = value;
   }
}
如果在getter/setter中没有要执行的操作,则可以使用,它将为您生成支持字段:

public Guid BlogId { get; set; }
您不能做的,以及您在这里真正尝试做的,是将不同的类型传递到属性中-要做到这一点,您需要在类上使用一个方法,即:

public bool TrySetBlogId(string newId)
{
    Guid id;
    var stringIsGuid = Guid.TryParse(newId, out id);

    if (stringIsGuid)
    {
        BlogId = id;
    }

    return stringIsGuid;
}

您只需要引入一个支持变量

private Guid\u blogId
并确保在
set
方法中设置该字段

public Guid BlogId 
{ 
get 
   { 
       return _blogId; 
   }

set
   {
       string blogIdstr = "FCA96EFB-D51C-4C41-9F85-3EEB9C50BDE7";
       Guid blogIdGuid = Guid.Empty;
       blogIdGuid = Guid.Parse(blogIdstr);

       _blogId = value;
   }
}

对于第一个,在BlogId中,返回BlogId,它激发返回的Getter。。。BlogId。吊杆,堆栈溢出。在公共getter中返回blogIdGuid,而不是BlogId

我猜第二个与第一个相关,但是如果没有更多的代码,我不能马上说出来


编辑:哎呀,误读了代码。是的,使用一个名为_blogId的支持类级属性,在setter中设置它,并在getter中返回它。

这是一个递归函数,没有退出条件,当然会溢出。
public Guid BlogId 
{ 
get 
   { 
       return _blogId; 
   }

set
   {
       string blogIdstr = "FCA96EFB-D51C-4C41-9F85-3EEB9C50BDE7";
       Guid blogIdGuid = Guid.Empty;
       blogIdGuid = Guid.Parse(blogIdstr);

       _blogId = value;
   }
}