C# "linking" classes
I'm starting a simple C# console solution via Mono on Mac OS X.
I have a Main.cs
file for starters, but I want to create a separate class and be able to access object of that class from my Main.cs
file.开发者_如何学JAVA
How can I access that class from the Main.cs
file?
Say my class name was Math
.
In my Main.cs
file, can I create a new object like so:
Math calculator = new Math()
Without referencing the class in the Main.cs
file in any way?
Or, do I have to use some sort of import statement/directive?
You need a using
statement if your Main and Math are in different name spaces, otherwise it just works. Below is an example. The using System
brings in the library that contains the Console
class, but no using
is required to use the Math
class.
Program.cs:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Math caclulator = new Math();
Console.WriteLine(caclulator.Add(1, 2));
}
}
}
Math.cs:
namespace ConsoleApplication1
{
class Math
{
public int Add(int x, int y)
{
return x + y;
}
}
}
There are two scenarios here. Either this class is in a separate dll (class library project), or under the same project. To reference within the same project not additional work is needed, other than referencing it with the correct namespace (as mentioned in other posts).
In the case of a separate dll, you need to add a refence to the project in the project definition. Most default projects come with a reference to System.dll
and other related libraries. It is recommended to name your dll's based on what namespaces are defined within it. If you have classes like Foo.Mathematics.IntMath
, Foo.Mathematics.DblMath
then I suggest you name it Foo.Mathematics.dll
.
When I was where you are, I picked up .NET Framework Essentials from O'Reilly and it had answers to all my questions at the time.
精彩评论