I have a class that defines a protected field. The protected field has a field initializer.
When I deserialize the concrete class, the field initializer is not run. Why? What is the best pattern to solve the problem? If I move the initialization into a constructor, the constructor is also not invoked.
[DataContract]
public class MyConcrete
{
// FIELD INITIALIZER DOES NOT RUN WHEN COMMENTED IN:
protected readonly Dictionary<int, string> myDict;// = new Dictionary<int, string>();
public MyConcrete()
{
myDict = new Dictionary<int, string>();
}
private bool MyMethod(int key)
{
return myDict.ContainsKey(key);
}
private int myProp;
[DataMember]
public int MyProp
{
get { return myProp; }
set { bool b = MyMethod(value); myProp = value; } // Call MyMethod to provoke error
}
}
ORIGINAL CLASS HIERARCHY
[DataContract]
public abstract class MyAbstract
{
// THIS INITIALIZER IS NOT RUN WHILE DESERIALIZING:
protected readonly Dictionary<int, string> myDict = new Dictionary<int, string>();
private bool MyMethod(int key)
{
return myDict.ContainsKey(key);
}
private int myProp;
[DataMember]
public int MyProp
{
get { return myProp; }
set { bool b = MyMethod(value); myProp = value; } // Call MyMethod to provoke error
}
}
[DataContract]
public class MyConcrete : MyAbstract
{
}
class Program
{
static void Main(string[] args)
{
string tempfn = Path.GetTempFileName();
MyConcrete concrete = new MyConcrete() { MyProp = 42 };
string data = concrete.SerializeToString<MyConcrete>();
MyConcrete rehydrated = SerializationHelper.DeserializeFromString<MyConcrete>(data);
}
}
SUPPORTING METHODS
static public string SerializeToString<T>(this T obj)
{
return SerializationHelper.SerializeToString<T>(obj);
}
static public string SerializeToString<T>(T obj)
{
DataContractSerializer s = new DataContractSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
s.WriteObject(ms, obj);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
string serialized = sr.ReadToEnd();
return serialized;
}
}
}
static public T DeserializeFromString<T>(string serializedDataAsString)
{
DataContractSerializer s = new DataContractSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(serializedDataAsString)))
{
object s2 = s.ReadObject(ms);
return (T)s2;
}
}
On deserialization neither the constructors nor the field initializers are called and a "blank" un-initialized object is used instead.
To resolve it you can make use of the OnDeserializing or OnDerserialized attributes to have the deserializer call a function with the following signature:
void OnDeserializing(System.Runtime.Serialization.StreamingContext c);
In that function is where you can initialize whatever was missed within the deserialization process.
In terms of convention, I tend to have my constructor call a method OnCreated() and then also have deserializating method call the same thing. You can then handle all of the field initialization in there and be sure it's fired before deserialization.
[DataContract]
public abstract class MyAbstract
{
protected Dictionary<int, string> myDict;
protected MyAbstract()
{
OnCreated();
}
private void OnCreated()
{
myDict = new Dictionary<int, string>();
}
[OnDeserializing]
private void OnDeserializing(StreamingContext c)
{
OnCreated();
}
private bool MyMethod(int key)
{
return myDict.ContainsKey(key);
}
private int myProp;
[DataMember]
public int MyProp
{
get { return myProp; }
set { bool b = MyMethod(value); myProp = value; }
}
}
Another approach is to access your field through a protected (in your example) property, and initialise the field using the null-coalescing (??) operator
protected Dictionary<int, string> myDict = new Dictionary<int, string>();
protected Dictionary<int, string> MyDict
{
get
{
return myDict ?? (myDict = new Dictionary<int, string>());
}
}
The downsides are that you lose the benefits of readonly, and need to make sure that you only access the value via the property.
Related
I have an abstract class like this:
public abstract class Records
{
public string Type;
public string Source;
public int Value;
protected Records(string type, string source, int value)
{
Type = type;
Source = source;
Value = value;
}
}
I would like to create many classes inheriting this class, and filling their Type field with a value coming from a static class like this:
public static class ContentTypesString
{
public static string DocumentNew { get { return "Document - New this Month"; }}
public static string HeadlinesNew { get { return "Headlines - New this Month"; }}
etc...
}
I would like to be able to create those child classes without having a test "if foo == "document" then type = ContentTypesString.DocumentNew" or an equivalent switch case (I really have a lot of cases)
Is there a design pattern that suits my needs?
EDIT : As several people pointed out, i should show how i create my instances.
private delegate SPListItemCollection Query(SPWeb web, DateTime startDate, DateTime endDate);
private readonly Query _queries;
#region Constructors
public QueryHandler(SPWeb web, DateTime startTimeSelectedDate, DateTime endTimeSelectedDate)
{
if (web == null) throw new ArgumentNullException("web");
_web = web;
_startTimeSelectedDate = startTimeSelectedDate;
_endTimeSelectedDate = endTimeSelectedDate;
RecordsList = new List<Records>();
// Query Invocation List
_queries = NumberPagePerMonthQuery.PreparedQuery;
_queries += NumberDocumentsPerMonthQuery.PreparedQuery;
_queries += NumberHeadlinesPerMonthQuery.PreparedQuery;
_queries += NumberLeaderboxPerMonthQuery.PreparedQuery;
_queries += NumberNewsPerMonthQuery.PreparedQuery;
_queries += NumberPagesModifiedPerMonthQuery.PreparedQuery;
_queries += NumberPicturesPerMonthQuery.PreparedQuery;
_queries += NumberTeasingPerMonthQuery.PreparedQuery;
}
#endregion Constructors
#region Public Methods
// what about NullReferenceException ? C#6 : item?.Foreach(item => {}); ?
/*** NO C#6 compiler in VS2012... ***/
public void Queries()
{
foreach (var del in _queries.GetInvocationList())
{
var queryresult =
(SPListItemCollection) del.DynamicInvoke(_web, _startTimeSelectedDate, _endTimeSelectedDate);
RecordsList.Add(new Records(del.Method.Name, _web.Title, queryresult.Count));
}
}
EDIT² :
The solution i chose
public List<IQuery> QueryList { get; } // no delegate anymore, and static classes became implementations of IQuery interface.
#region Constructors
public QueryHandler(SPWeb web, DateTime startTimeSelectedDate, DateTime endTimeSelectedDate)
{
if (web == null) throw new ArgumentNullException("web");
_web = web;
_startTimeSelectedDate = startTimeSelectedDate;
_endTimeSelectedDate = endTimeSelectedDate;
RecordsList = new List<Records>();
QueryList = new List<IQuery>
{
new NumberDocumentsPerMonthQuery(),
new NumberHeadlinesPerMonthQuery(),
new NumberLeaderboxPerMonthQuery(),
new NumberNewsPerMonthQuery(),
new NumberPagePerMonthQuery(),
new NumberPagesModifiedPerMonthQuery(),
new NumberPicturesPerMonthQuery(),
new NumberTeasingPerMonthQuery()
};
}
#endregion Constructors
#region Public Methods
// what about NullReferenceException ? C#6 : item?.Foreach(item => {}); ?
/*** NO C#6 compiler in VS2012... ***/
public void Queries()
{
foreach (var query in QueryList)
{
var queryresult = query.PreparedQuery(_web, _startTimeSelectedDate, _endTimeSelectedDate);
RecordsList.Add(query.CreateRecord(_web.Title, queryresult.Count));
}
}
Record class follow the implementation suggested by #dbraillon
Implementation of IQuery interface were added the method :
public Records CreateRecord(string source, int value)
{
return new ModifiedPagesPerMonthRecord(source, value); //or another child of Record class.
}
And voilĂ . Thank you all for the help.
You want to make collection of records, by string code of object type, and parameters.
One of many way to do it - use builder.
Firstly we need to configurate builder:
var builder = new RecordBuilder()
.RegisterBuilder("document", (source, value) => new Document(source, value))
.RegisterBuilder("headlines", (source, value) => new Headlines(source, value));
here we specify how to build record with code "document" and "headlines".
To build a record call:
builder.Build("document", "source", 1);
Builder code can by something like this
(here we look if we know how to build record of the passed type and make it):
public class RecordBuilder
{
public Records Build(string code, string source, int value)
{
Func<string, int, Records> buildAction;
if (recordBuilders.TryGetValue(code, out buildAction))
{
return buildAction(source, value);
}
return null;
}
public RecordBuilder RegisterBuilder(string code, Func<string, int, Records> buildAction)
{
recordBuilders.Add(code, buildAction);
return this;
}
private Dictionary<string, Func<string, int, Records>> recordBuilders = new Dictionary<string, Func<string, int, Records>> ();
}
public class Document : Records
{
public Document(string source, int value) : base(ContentTypesString.DocumentNew, source, value)
{
}
}
public class Headlines : Records
{
public Headlines(string source, int value) : base(ContentTypesString.HeadlinesNew, source, value)
{
}
}
Is that what you need ?
public abstract class Records
{
public string Type;
public string Source;
public int Value;
protected Records(string type, string source, int value)
{
Type = type;
Source = source;
Value = value;
}
}
public class DocumentRecords : Records
{
public DocumentRecords(string source, int value)
: base(ContentTypesString.DocumentNew, source, value) // use here
{
}
}
public class HeadlinesRecords : Records
{
public HeadlinesRecords(string source, int value)
: base(ContentTypesString.HeadlinesNew, source, value) // use here
{
}
}
public static class ContentTypesString
{
public static string DocumentNew { get { return "Document - New this Month"; } }
public static string HeadlinesNew { get { return "Headlines - New this Month"; } }
}
Title says it all. Reducing access through access modifiers only prevents reinitialising the property; It doesn't prevent elements from becoming global state (bad practice). I know there's a workaround with List<T>'s but what should I do for any other indexed collection?
public class Start
{
public static void main()
{
//CODE SMELL AHEAD
AttendanceManager.MuteStatuses[0] = new KeyValuePair <string, string> ("", "");
}
}
public static class AttendanceManager
{
public static HybridDictionary MuteStatuses
{
get
{
playersMuteStatuses.Add ("", "");
return playersMuteStatus;
}
}
private static HybridDictionary playersMuteStatus = new HybridDictionary();
}
Dont use HybridDictionary. We do have IReadOnlyDictionary<T>
private Dictionary<string, string> playersMuteStatus = new... ;
public IReadOnlyDictionary<string, string> MuteStatuses
{
get
{
return playersMuteStatus as IReadOnlyDictionary<string, string>;
}
}
Write helper methods:
public static void AddMuteStatus()
=> playersMuteStatus.Add("", "");
public static object GetMuteStatus(object idx)
=> return playersMuteStatus[idx];
I have something like this. How can i return value form anonymous method?
returnRate = d;. For example let i have some class which get's messages from server. I want to process those messages in classes Cars and Bicycles is that clearly now?
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Cars c = new Cars();
Bicycles b = new Bicycles();
}
}
public class Cars
{
public Cars()
{
GetData G1 = new GetData();
Dictionary<string, string> D1 = new Dictionary<string, string>();
G1.ProcessCars(ref D1);
}
}
public class Bicycles
{
public Bicycles()
{
GetData G2 = new GetData();
Dictionary<string, string> D2 = new Dictionary<string, string>();
G2.ProcessBicycles(ref D2);
}
}
public class Singleton
{
private static Singleton instance;
public Dictionary<string, Action<MessageEventArgs>> Handle;
private Singleton()
{
Handle = new Dictionary<string, Action<MessageEventArgs>>();
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
public class GetData
{
private Client socket;
public GetData()
{
socket = new Client("http://echo.jsontest.com/bicycles/10");
socket.Message += Message;
}
public void ProcessBicycles(ref Dictionary<string, string> returnRate)
{
Singleton.Instance.Handle.Add("bicycles", (m) =>
{
Dictionary<string, string> d = m.Message.Json.GetFirstArgAs<Dictionary<string, string>>() as Dictionary<string, string>;
//returnRate = d;
});
}
public void ProcessCars(ref Dictionary<string, string> returnRate)
{
Singleton.Instance.Handle.Add("cars", (m) =>
{
Dictionary<string, string> d = m.Message.Json.GetFirstArgAs<Dictionary<string, string>>() as Dictionary<string, string>;
//returnRate = d;
});
}
private void Message(object sender, MessageEventArgs e)
{
if (Singleton.Instance.Handle.ContainsKey(e.Message.Event))
{
Singleton.Instance.Handle[e.Message.Event](e);
}
}
}
}
You'll have to pass in the Action yourself, rather than creating it with a ref parameter. So your Add method simply becomes:
public void Add(Action<string> action) {
Handle.Add("1", action);
}
You can call it like this:
Add(m => ReturnRate = m);
This is a kind of Callback function, which can be used for a kind of asynchronous programming. However, it might be worth your time to read about async and await. If you could give us more information about what your scenario exactly is, we might be able to give you more hints.
If you have to use a ref parameter (for some strange reason), I think you're out of luck...
You should use Func<string,string> instead Action
Action<string> means void function(string s)
Func<string,string> means string function(string s)
However it depends on usage you want to achieve.
This is because the used variables that are used in the the anonymous method body but are outside of it, will be public fields in the generated class made by the compiler. But you can introduce a local variable to make it compilable:
public void Add(ref string rate)
{
string r = rate;
Handle.Add("1", (m) =>
{
Console.WriteLine(m);
r = m;
});
rate = r;
}
And the compiler will generate this in the background:
public void Add(ref string rate)
{
<>c__DisplayClass1 CS$<>8__locals2 = new <>c__DisplayClass1();
CS$<>8__locals2.r = rate;
this.Handle.Add("1", new Action<string>(CS$<>8__locals2.<Add>b__0));
rate = CS$<>8__locals2.r;
}
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
public string r;
public void <Add>b__0(string m)
{
Console.WriteLine(m);
this.r = m;
}
}
Note: Though this can be compiled, it will not work as you expect, because calling the outer Add will not execute the delegate added by Handle.Add. To return the m from the inner delegate you must use a Func instead.
You should use Func<string,string> (delegate Func<in T,out TResult>) which is equivalent to some function that takes in string and returns string
for eg:-
private string MyFunction(string inputstring){}
Whereas Action<string> (delegate Action<in T>) corresponds to a function which only takes input and returns nothing
private void MyFunction(string inputstring){}
You can modify your code to something like
private Dictionary<string, Func<string,string>> Handle;
private string ReturnRate;
public data()
{
Handle = new Dictionary<string, Func<string,string>>();
Add(ref ReturnRate);
Handle["1"]("MyValue");
Console.WriteLine(ReturnRate);
}
public void Add(ref string rate)
{
string somevalue=rate;
Handle.Add("1", (m) =>
{
Console.WriteLine(m);
somevalue= m;
return m;
});
}
I want to implement a wrapper class for a Dictionary that maps a Type to a generic List of that Type. For example:
**Key** **Value**
typeof(InterfaceA), List<InterfaceA>
typeof(InterfaceB), List<InterfaceB>
typeof(MyClass), List<MyClass>
...
I then want to interact with the wrapper class by using types.
public void NewEntry<T>()
{
MyDict.Add(typeof(T), new List<T>());
}
public List<T> GetEntry<T>()
{
return MyDict[typeof(T)];
}
public void RemoveEntry<T>()
{
MyDict.Remove(typeof(T));
}
Is there any elegant way to do this?
EDIT: to clarify, the point of this is so that with
GetEntry<MyInterface>()
the items in the list are guaranteed to follow the contract of MyInterface. Each entry would have a different Type key, and each List of items would follow the contract of that Type.
You could use the following static class
public static class GenericLists
{
private static Dictionary<Type, object> MyDict = new Dictionary<Type, object>();
public static void NewEntry<T>()
{
MyDict.Add(typeof(T), new List<T>());
}
public static List<T> GetEntry<T>()
{
return (List<T>)MyDict[typeof(T)];
}
public static void RemoveEntry<T>()
{
MyDict.Remove(typeof(T));
}
}
Or you could use
public class GenericLists<T>
{
private Dictionary<Type, List<T>> MyDict = new Dictionary<Type, List<T>>();
public void NewEntry()
{
MyDict.Add(typeof(T), new List<T>());
}
public List<T> GetEntry()
{
return MyDict[typeof(T)];
}
public void RemoveEntry()
{
MyDict.Remove(typeof(T));
}
}
if you really want to initialize it, but I think the static will work better.
If you're willing to store everything statically, you can use the type system:
static class MyDict {
private static class Data<T> {
public static readonly List<T> items = new List<T>();
}
public static List<T> Get<T>() { return Data<T>.items; }
public static void Add<T>(T item) { Data<T>.items.Add(item); }
}
Note that this makes it impossible to remove a key (you can't unload a type), although you can Clear() it.
You can do it as an instance-based class also (see below), but my preference, if it works for you, is to use a static variable in a static class as SLaks demonstrated in the "use the type system" post.
public class GenericTypeListDictionary
{
private readonly Dictionary<Type, object> _dictionaryOfLists = new Dictionary<Type, object>();
public List<T> NewEntry<T>()
{
var newList = new List<T>();
_dictionaryOfLists.Add(typeof(T), newList);
return newList;
}
public List<T> GetEntry<T>()
{
object value;
if (_dictionaryOfLists.TryGetValue(typeof(T), out value))
{
return (List<T>)value;
}
return null;
}
public void RemoveEntry<T>()
{
_dictionaryOfLists.Remove(typeof(T));
}
}
I have an abstract base class that holds a Dictionary. I'd like inherited classes to be able to access the dictionary fields using a convenient syntax. Currently I have lots of code like this:
string temp;
int val;
if (this.Fields.TryGetValue("Key", out temp)) {
if (int.TryParse(temp, out val)) {
// do something with val...
}
}
Obviously I can wrap this in utility functions but I'd like to have a cool, convenient syntax for accessing the dictionary fields where I can simply say something like:
int result = #Key;
Is there any way to do something like this in C# (3.5)?
You could add an indexer to your class and pass the indexer's parameter through to the dictionary.
class Foo
{
// Initialized elsewhere
Dictionary<String,String> Fields;
public Int32 this[String key]
{
String temp = null;
Int32 val = 0;
if (this.Fields.TryGetValue(key, out temp)) {
Int32.TryParse(temp, out val);
}
return val;
}
}
Then given an instance of Foo called foo you could do this:
Int32 value = foo["Key"];
How about an extension method?
public static int TryGetInt(this IDictionary dict, string key)
{
int val;
if (dict.Contains(key))
{
if (int.TryParse((string)dict[key], out val))
return val;
else
throw new Exception("Value is not a valid integer.");
}
throw new Exception("Key not found.");
}
The closer you can get to a nice syntax is using extension methods:
public static class MyDictExtensionMethods
{
public static T Get<T>(this Dictionary<string, object> dict, string key)
where T: IConvertible
{
object tmp;
if (!dict.TryGetValue(key, out tmp))
return default(T);
try {
return (T) Convert.ChangeType(tmp, typeof(T));
} catch (Exception) {
return default(T);
}
}
}
Usage:
int val = this.Fields.Get<int>("Key");
You can then create additional overloads for specific types (i.e.: types that does not implement IConvertible and need specific conversion).
Assuming that it's not always an int you want (if it is, then why isn't it a Dictionary<string, int>?) - I think something like this works and gets pretty close:
int i = #int["Key"];
string s = #string["Key"];
object o = #object["Key"];
This combines the fact that identifiers can be prefixed with # (it's usually optional, but it's required if your identifier is a reserved keyword, like int or string) with the default indexed parameter from Andrew Hare's answer.
It does require another class to be used to get the indexing - though if you wanted to use parens instead of square brackets for the key name, you could use methods instead:
int i = #value<int>("Key");
Implementation would be something like:
class DerivedClass : BaseClass {
void Main() {
int i = #int["Key"];
}
}
abstract class BaseClass {
private Dictionary<string, string> D { get; set; }
protected Indexer<int> #int = new Indexer<int>(s => int.Parse(s), this);
protected Indexer<string> #string = new Indexer<string>(s => s, this);
protected Indexer<object> #object = new Indexer<object>(s => (object)s, this);
protected class Indexer<T> {
public T this[string key] {
get { return this.Convert(this.BaseClass.D[key]); }
}
private T Convert(string value) { get; set; }
private BaseClass { get; set; }
public Indexer(Func<T, string> c, BaseClass b) {
this.Convert = c;
this.BaseClass = b;
}
}
}
Or, the method route:
class DerivedClass : BaseClass {
void Main() {
int i = #value<int>("key");
}
}
abstract class BaseClass {
private Dictionary<string, string> D { get; set; }
protected T #value<T>(string key) {
string s = this.D[s];
return Convert.ChangeType(s, typeof(T));
}
}
After reading through the language spec - if you're not tied to #, _ is a legal identifier. Combine that with indexers and you get:
int i = _["key"];