Pointers to class of root type in C#
I'm sorta new to C# and don't know how to implement pointer interfaces for class types that I am defining. Its super easy to do in C++ (though, I've not done it since college) or C (where I do it all the time), but I'm having trouble not getting errors in C#.
Its clearer in example. Suppose you want to implement a family tree:
class person{
person* mom;
person* dad;
string Name;
string Birthdate;
person[] children;
//...constructors, destructors, methods etc...
}
VS2010 Tells me that "Cannot declare a pointer to a managed type" I don't want to know of good implementation开发者_如何学Gos for this kind of problem (since I will be making the structure pretty custom and not anything at all like a tree), just how to declare pointers to objects of the type that contains the pointer (in C#) Is this the wrong way to use a class?
Remove the pointers and your code will work fine. In C#, classes already are references, there is no such thing as a value class
, that construct is called struct
.
You don't need to declare them as pointers, just as the type:
class person{
person mom;
person dad;
string Name;
string Birthdate;
// Though I would probably use ICollection<Person> or IList<person>
person[] children;
//...constructors, destructors, methods etc...
}
Since person
is a reference type, that's all you need.
In general, pointers are not needed in c# (though you can use them in code marked as unsafe
).
Whenever you have a variable of a class
type it's automatically a reference. A reference in C# behaves pretty much like a pointer in C++, except that you can't do arithmetic with it.
Unlike C++ you don't decide to use references/values when you declare a variable, but when you declare a type. Being a reference or a valuetype is an inherent property of a type.
Uhm...you don't need pointers on C# (to do this). If your intent is to create a "tree", just remove the "*" sign in front of the type name.
hope it helps.
C# code does not use pointers. While it's possible to write C# that makes use of pointers, this code is called "unsafe" and there is very little, if any, reason to use this feature in ordinary code.
All classes in any of the .NET languages are called "reference types". This means that wherever you see that type used in code for a variable, member, or parameter type, then the value of that object is a reference that (for lack of a better term) points to an instance of the type. In other words, they function in very similar fashion to pointers, though only in the most basic sense (there is no such thing as "reference arithmetic", for example).
To make a long story short, simply remove the asterisk from your declarations and your code will work how you originally intended for it to. While there are some stylistic issues with your code (.NET code is conventionally PascalCased, not camelCased, and it's best not to expose member variables directly, but rather use properties), that should get you going.
精彩评论