For a program I'm making I'm using object
to hold the value of HTML attributes. There's a bunch if things I do with these values in the whole program. So I would basically like to create an alias for object
whenever is used to hold values of HTML attributes to something like AttrValue
just to make the program more clear, and to be able to easily add functionality if needed. These objects are used on critical-performance parts of the program, so I'm not sure if making a class instead of a struct would be the best idea. What would it be the best solution here, if performance is the main concern (more than 开发者_如何学Pythonclearness actually)?
You can create a type alias like using AttrValue = System.Object;
. However, this alias will only exist in your source code. There's nothing stopping you from using, say, object
or string
where you need an AttrValue
. You won't be able to add properties or methods onto your AttrValue
alias: it will be an alias for object
and not a class in its own right.
You're probably better off introducing AttrValue
as a class in its own right, presumably as a wrapper for a value of type object
. It might have a single field (of type object
), and a constructor that takes one object
parameter.
Regarding struct vs. class, I wouldn't worry about this. You almost never need a struct in .NET code: the garbage collector is capable of handling lots of small class instances without noticeable overhead, and structs have their own oddities (mainly because what looks like the same instance in source code can easily end up being two separate copies at run time).
Well, the first question is... Why are you using object
?
HTML is text, and therefore all html attributes are strings. You may want to convert them to some other data type (ints or enums), but storing them as objects isn't going to help with that.
If inheritance were a performance issue, .NET would have some major problems. Inheritance is a fundamental concept in C# and it works and performs splendidly. I suggest you create a descendant class and use that.
public class HtmlAttrValue: System.Object;
If you really wanted to, you can also create a type alias in C#, though not as well as some other languages. A type alias in C# only applies to the file in which it is defined.
using HtmlAttrValue = System.Object;
This is poorly supported and not very well known and I don't recommend it. You might also find it more convenient to treat your HTML as XHTML (if possible) and use some of the existing XML types and classes to do your work for you.
精彩评论