簡體   English   中英

c#未知輸入參數類型?

[英]c# unknown input parameter type?

我有一個通用函數static Log<T>(T Log) 我想檢查T類型並決定下一步該做什么。

這是我到目前為止所得到的:

public static void Log<T>(T log)
{
    switch (typeof(log))
    { ... }
}

我究竟做錯了什么? 我的錯誤是typeof(log)不起作用。

您需要詢問T不是log - 並且交換機必須是基本類型(或string ),因此請查看類型Name或可能是FullName

switch(typeof(T).Name){...}

你也可以在T的實例上調用GetType

switch(log.GetType().Name){...}

兩者都會產生相同的結果

switch (expression)
{

}

expression =一個整數或字符串類型表達式(來自MSDN)

http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.71).aspx

typeof關鍵字不返回這些。 您不能使用log.GetType()因為您需要滿足以上Type不適合的條件。

為了安全起見,我將此限制為if具有相應類型的語句將實現相同的目的。

static void a<T>(T b)
{
  if (typeof(T) == typeof(B))
    Console.WriteLine("T is B");
  else if(typeof(T) == typeof(C))
    Console.WriteLine("T is C");
}

編輯:

如果你有參數,你有:

  public class Vehicle 
  {
    public virtual int MoveVehicle() 
    {
       //Do Logic
       return 0;
    }
  }
  public class Car : Vehicle { }

而且你想要一個通用的方法移動Vehicle你可以做一些叫做generic type constraints東西

static void a<T>(T b) where T : Vehicle
{
    int newPosition = b.MoveVehicle();
}

http://msdn.microsoft.com/en-us/library/bb384067.aspx

T必須是現在的車輛,因此您可以訪問車輛中的方法。 您可以將汽車傳遞給方法,它仍然可以調用MoveVehicle方法。

  a<Vehicle>(new Car());

使用GetType函數

  switch(log.GetType().ToString()) {....}

insof of typeof().

您無法在System.Type上進行切換,也無法對變量進行typeof 你能做的是:

static Dictionary<Type, TypeEnum> Types = new Dictionary<Type, TypeEnum>() { { typeof(TypeA), TypeEnum.TypeA } }; // Fill with more key-value pairs

enum TypeEnum
{
    TypeA
    // Fill with types
}


public static void Log<T>(T log)
{
    TypeEnum type;
    if (Types.TryGetValue(typeof(T), out type)) {
        switch (type)
        { ... }
    }
}

這也是我所知道的最快的解決方案。 字典查找速度非常快。 您也可以使用System.String (通過Type.NameType.FullName )執行此操作,但它會更慢,因為Equals (確定)和GetHashCode (取決於它們的實現)的字符串方法較慢。

當您使用String時,它與使用String上的開關時編譯器的操作相同。

switch(typeof(T).FullName) // Converted into a dictionary lookup
{ ... }

更多的想法

根據您要歸檔的內容,您應該知道您也可以使用約束:

public interface ILogItem
{
    String GetLogData();
    LogType LogType { get; }
}

public void Log<T>(T item) 
    where T : ILogItem
{
    Debug.WriteLine(item.GetLogData());
    // Read more data
    switch (item.LogType)
    { ... }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM