Question on my Class implemention in C#
Currently i have a class which has only properties
class MyEntity
{
public string FirstName { get; set; }
开发者_运维知识库 public string LastName { get; set; }
}
In my other class, I use to set the values like
MyEntity objEnt = new MyEntity();
objEnt.FirstName="abc";
objEnt.LastName = "edf";
The reason i have the class MyEntity
with only properties is to ensure adherence.
Question here is, if this approach is correct? I can have multiple instances of MyEntity
Can i use Static Class for this? How can i use Generics in this?
BTW the implementation is in C#
Thanks in advance
Cheers,
Karthik
- You can't use a static class, as you have state. Static classes can only consist of static members.
- It's hard to see how you'd use generics here
Personally I prefer types to be immutable where possible - for example by giving MyEntity
a constructor with two parameters, and removing the public setters from the properties. (Whether you keep private setters which you just don't use outside the constructor, or move to "proper" readonly fields and readonly properties is another choice.) However this mutable type may be absolutely fine for you - it's impossible to say without knowing what you're trying to do.
Note that you can use object initializers to make your initialization simpler, while you're using the mutable type:
MyEntity objEnt = new MyEntity { FirstName = "abc", LastName = "edf" };
(If you made the type immutable, you'd pass the values in the constructor. You could still use names via C# 4's "named arguments" feature, if you're using C# 4.)
As already said it depends from your needs. Just to note that you can't use static class as you want to have multiple instances and also there can be issues with synchronization while access from multiple threads.
As for generics ... whats for you need it here ?
I had an answer half typed, but then Jon answered so my answer in its current form became pointless....
I will offer a counterpoint on Jon's answer though. Think carefully before using immutable objects - they are good from some perspectives, but you will quickly run into trouble if using them for binding to editable fields, or if serializing them (either to storage or for transferring, ie WCF web service calls).
Here is a quick and dirty use of generics for your unspecified DTO I am assuming.
class MyEntity<T>
{
public T value { get; set; }
}
精彩评论