C # and reflection
I'm new to C #, although not programming, so please forgive me if I confuse things a bit - this is completely unintentional. I wrote a fairly simple class called "API" that has several public properties (accessors / mutators). I also wrote a test console application that uses reflection to get an alphabetical list of the names and types of each property in the class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using MyNamespace; // Contains the API class
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi");
API api = new API(1234567890, "ABCDEFGHI");
Type type = api.GetType();
PropertyInfo[] props = type.GetProperties(BindingFlags.Public);
// Sort properties alphabetically by name.
Array.Sort(props, delegate(PropertyInfo p1, PropertyInfo p2) {
return p1.Name.CompareTo(p2.Name);
});
// Display a list of property names and types.
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, propertyInfo.PropertyType);
}
}
}
}
Now I need a method that iterates over the properties and concatenates all values ββtogether in a querystring. The problem is I would like to make it a function of the API class itself (if possible). I'm wondering how static constructors have something to do with solving this problem, but I've only worked with C # for a few days and haven't been able to figure it out.
Any suggestions, ideas and / or code samples are greatly appreciated!
source to share
It has nothing to do with constructors static
. You can do it with static
methods :
class API {
public static void PrintAPI() {
Type type = typeof(API); // You don't need to create any instances.
// rest of the code goes here.
}
}
You can call it with:
API.PrintAPI();
You don't use instances when you call methods static
.
Update: . To cache the result, you can do this on the first call or in the initializer static
:
class API {
private static List<string> apiCache;
static API() {
// fill `apiCache` with reflection stuff.
}
public static void PrintAPI() {
// just print stuff from `apiCache`.
}
}
source to share