Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

c# - How to implement an inherited Dictionary over WCF

I’m trying to implement a dictionary for use with WCF. My requirements are:

  • actual (private variable or base class) type equivalent to Dictionary
  • Comparer = System.StringComparer.InvariantCultureIgnoreCase
  • Custom (override/new) Add(key, value) method (to include validations).
  • Override ToString()
  • Use of the same type on both the client and host

I’ve attempted using this class in a common project shared by the WCF host and client projects:

[Serializable]
public class MyDictionary : Dictionary<string, object>
{
  public MyDictionary()
    : base(System.StringComparer.InvariantCultureIgnoreCase)
  { }

  public new void Add(string key, object value)
  { /* blah */ }

  public override string ToString()
  { /* blah */ }
}

[DataContract]
[KnownType(typeof(MyDictionary))]
[KnownType(typeof(object[]))]
[KnownType(typeof(double[]))]
[KnownType(typeof(string[]))]
[KnownType(typeof(DateTime[]))]
public class ResultClass
{
  public object Value{ get; set; }
  /* More properties */
}
public class ParmData
{
  public object Value{ get; set; }
  /* More properties */
}
[DataContract]
[KnownType(typeof(MyDictionary))]
[KnownType(typeof(object[]))]
[KnownType(typeof(double[]))]
[KnownType(typeof(string[]))]
[KnownType(typeof(DateTime[]))]
public class ParameterClass
{
  public List<ParmData> Data{ get; set; }
  /* More properties */
}

[OperationContract]
ResultClass DoSomething(ParameterClass args);

Results:

  • When I pass MyDictionary as one of the ParameterClass.Data.Value elements, I get a missing KnownType exception.
  • I can safely return MyDictionary in the ResultClass, but it is no longer my type. It is just a Dictionary, and is not castable to MyDictionary. Also comparer = System.Collections.Generic.GenericEqualityComparer<string>, not the case insensitive comparer I’m looking for.

The help I’m asking for is to either fix my failed attempt, or a completely different way to achieve my stated requirements. Any solution should not involve copying one dictionary to another.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add CollectionDataContract to the Dictionary class:

For more information on using collection data contracts to implement dictionaries, check this link:

http://msdn.microsoft.com/en-us/library/aa347850.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...