C#将类作为参数传递

时间:2018-11-16 01:06:42

标签: c# class parameters

我希望能够动态循环遍历以下名称空间中的所有参数,以将名称和值写入将写入结果的文件中。设置的值在程序开始时设置。将结果写入文件的函数位于单独的命名空间中,因此我想将类作为参数传递给函数。

This post与我的问题不太一样,因为我想使用现有类中的值。

我已经看过使用Reflection的情况,但是无法正常工作,因为在写文件时命名空间“找不到”,并且不希望包含using指令,因为它会使情况变得复杂依赖关系。我还查看了Activator类,但这将创建对象的新实例,并且我将不得不重新读取参数的值。也许这是最好的选择。

Settings.cs

namespace Globalsettings
{

    public static class FileSettings
    {
        /* Filenames for each required file. */
        public static string dataFile = null;
        public static string geometryFile = null;
        public static string temporarySpeedRestrictionFile = null;
        public static string trainListFile = null;                  /* File only required if includeAListOfTrainsToExclude is TRUE. */                                                                    
        public static List<string> simulationFiles = new List<string>(new string[6]);
        public static string aggregatedDestination = null;

    }

    public static class Settings
    {

    /* Data boundaries */
    public static DateTime[] dateRange;                 /* Date range of data to include. */
    public static bool excludeListOfTrains;             /* Is a list of trains that are to be excluded available. */

    /* Corridor dependant / Analysis parameters */
    public static double startKm;                       /* Start km for interpoaltion data. */
    public static double endKm;                         /* End km for interpolation data. */
    public static double interval;                      /* Interpolation interval (metres). */
    public static bool IgnoreGaps;                      /* Will the interpolation ignore gaps in the data (ie. gaps wont be interpolated through) */
    public static double minimumJourneyDistance;        /* Minimum distance of a train journey to be considered valid. */
    public static bool trainsStoppingAtLoops;           /* Analyse the performance of the trains as they stop at the loops. */

    /* Processing parameters */
    public static double loopSpeedThreshold;            /* Cuttoff for the simulation speed, when comparing the train to the simualted train. */
    public static double loopBoundaryThreshold;         /* Distance either side of the loop to be considered within the loop boundary (km). */
    public static double TSRwindowBoundary;             /* Distance either side of the TSR location to be considered within the TSR boundary (km). */
    public static double timeThreshold;                 /* Minimum time between data points to be considered a seperate train. */
    public static double distanceThreshold;             /* Minimum distance between successive data points. */

    /* Simulation Parameters */
    public static double Category1LowerBound;           /* The lower bound cuttoff for the underpowered trains. */
    public static double Category1UpperBound;           /* The upper bound cuttoff for the underpowered trains. */
    public static double Category2LowerBound;           /* The lower bound cuttoff for the overpowered trains. */
    public static double Category2UpperBound;           /* The upper bound cuttoff for the overpowered trains. */

    public static analysisCategory analysisCategory;
    public static trainOperator Category1Operator = trainOperator.Unknown;
    public static trainOperator Category2Operator = trainOperator.Unknown;
    public static trainOperator Category3Operator = trainOperator.Unknown;
    public static trainCommodity Category1Commodity = trainCommodity.Unknown;
    public static trainCommodity Category2Commodity = trainCommodity.Unknown;
    public static trainCommodity Category3Commodity = trainCommodity.Unknown;
    public static trainType Category1TrainType = trainType.Unknown;
    public static trainType Category2TrainType = trainType.Unknown;
    public static trainType Category3TrainType = trainType.Unknown;


}

}

是否可以将类传递给这样的函数?

writeSettings(Filesettings fileS, Settings s)
{
    for (int i = 0; i < fileS.Count(); i++)
    {
        Console.WriteLine(fileS[i].Name,": ",fileS[i].value);
    }

    for (int i = 0; i < s.Count(); i++)
    {
        Console.WriteLine(s[i].Name,": ",s[i].value);
    }
}

1 个答案:

答案 0 :(得分:2)

类只是一种类型。您通过这样声明您的方法来传递类型

void writeSettings(Type[] types)
{

并这样称呼它:

writeSettings(new Type[] { typeof(Settings), typeof(FileSettings) });

您也可以使用params获得更方便的语法:

void writeSettings(params Type[] types)
{

writeSettings(typeof(Settings), typeof(FileSettings) ); //Don't need to build an array

无论如何,我编写了一些代码,将您的属性放入字典中:

public static Dictionary<FieldInfo,object> ReadStaticFields(params Type[] types)
{
    return types
        .SelectMany
        (
            t => t.GetFields(BindingFlags.Public | BindingFlags.Static)
        )
        .ToDictionary(f => f, f => f.GetValue(null) );
}

您可以像这样使用它:

var settings = ReadStaticFields
(
    typeof(Globalsettings.Settings), 
    typeof(Globalsettings.FileSettings)
);

foreach (var s in settings)
{
    Console.WriteLine
    (
        "{0}.{1} = {2}({3})", 
        s.Key.DeclaringType, 
        s.Key.Name, 
        s.Value, 
        s.Key.FieldType.Name
    );
}