4

我有这个属性的课程

public bool IsDeleted { get; internal set; }

我在一些 WCF 服务上使用这个类,玩这个类的一些实例。获得类的实例后,所有其他公共属性都是可见的,除了 IsDeleted。如果我将 setter 公开,IsDeleted 也可以。

对这种奇怪的行为有任何想法吗?

4

1 回答 1

6

Most all serialization methods in .NET (including WCF) require a accessible getter and setter to work because it must be able to set the property to a value when it desearalizes the incoming field.

There is a work around, you can mark the backing store private member as the serialization field instead.

[DataContract]
class Foo
{
    [DataMember(Name="IsDeleted")]
    private bool _isDeleted;

    public bool IsDeleted 
    { 
       get { return _isDeleted; }
       internal set { _isDeleted = value; } 
    }
}

However, if your client does not have a refrence to Foo as a refrence DLL it will create a auto-generated proxy that will will look like.

class Foo
{
    public bool IsDeleted { get; set; }
}

To prevent that from happening make sure metadata publishing is turned off and you distribute a DLL with Foo to all clients who will consume your WCF service.


If you don't want to pass around a DLL you can use the workaround Silvermind mentioned in the comments by having the setter do nothing and having a internal method to set the backing member.

[DataContract]
class Foo
{
    private bool _isDeleted;

    public bool IsDeleted 
    { 
       get { return _isDeleted; }
       set {  } 
    }

    internal void SetIsDeletedInternal(bool value)
    {
        _isDeleted = value;
    }
}

However note that if you do this and the client passes a Foo object to you this will always force set _isDeleted to default(bool) on the object you receive from the client.

于 2013-11-12T18:37:24.380 回答