0

我正在使用 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);
   }
}

这个在 blog.cs 中...

public override Guid Id
{
get { return base.Id; }
set
{
    base.Id = value;
    base.BlogId = value;
}
}

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

4

3 回答 3

1

For the first one, in BlogId, you're returning BlogId, which fires the Getter that returns... BlogId. Boom, stack overflow. Return blogIdGuid in your public getter instead of BlogId.

I'm guessing the second one is related to the first, but without more code I can't tell offhand.

Edit: Whoops, misread the code. Yeah, use a backing class-level property called _blogId and set that in the setter and return it in the getter.

于 2013-10-22T17:40:50.950 回答
0

You just need to introduce a backing variable

private Guid _blogId; and be sure to set that field in your set method

public Guid BlogId 
{ 
get 
   { 
       return _blogId; 
   }

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

       _blogId = value;
   }
}
于 2013-10-22T17:40:49.963 回答
0

您的get方法正在调用自身,并且您的set方法本质上是通过为该方法设置一个本地值来发出无操作。如果你想在 getter 和 setter 内部做一些事情,你需要一个属性的支持字段:

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

   set
   {
       //some operation against value here, Validate(value), etc.
       _blogId = value;
   }
}

如果您在 getter/setter 中没有要执行的操作,则可以使用auto property,它将为您生成支持字段:

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;
}
于 2013-10-22T17:35:30.990 回答