[英]Return Different Types Within One Function C#
我正在創建一個項目數據管道,我需要從一個類中返回不同的類型
在這個課程中,我有很多字典可以保存和分隔要加載的元素/內容,但是我需要一種用單個字符串返回它們的方法...因為我不熟悉這些Type函數,所以我迷路了關於如何正確返回內容
我需要在一個單獨的類中進行此操作,以便以后可以進行XML序列化
這就是我現在所擁有的
DataClass contents;
public T ReturnType<T>(string asset)
{
if(typeof(T) == typeof(int))
{
return contents.Integers[Asset];
}
if(typeof(T) == typeof(float))
{
return contents.Floats[Asset];
}
if(typeof(T) == typeof(double))
{
return contents.Doubles[Asset];
}
return default(T);
}
它將允許我使用基本的Object類來解析內容,但我不希望任何內容在傳輸過程中丟失,因此我對使用此方法感到厭倦
我的問題是如何在使用此類功能進行序列化的類中返回某些類型的不同對象之一
如果我想使用以前的功能來獲取類中的內容,例如
public Object someobject;
//button event handler to change the current object
//preferably this would be changed depending on the object i would be calling
//but this should do for showing how it is supposed to work
public void ChangeCurrentObject(event e)
{
someobject = (Object)ReturnType<Object>("23rdObject");
}
它向名為“ ReturnType”的函數發送一個字符串,並返回一個具有各自字典的對象(即,int,float等)
在這種情況下,泛型只會幫助您不要為每種資產類型編寫不同的方法。 您也可以使用此方法來使其更具模塊化。
static class Assets
{
public interface IAssetHandler<out T>
{
T GetAsset(string name);
}
private static readonly Dictionary<Type,object> _handlers=new Dictionary<Type, object>();
public static T GetAsset<T>(string name)
{
object assetHandler;
if(!_handlers.TryGetValue(typeof(T),out assetHandler))
{
throw new Exception("No handler for that type of asset");
}
return (assetHandler as IAssetHandler<T>).GetAsset(name);
}
public static void RegisterAssetHandler<T>(IAssetHandler<T> handler)
{
_handlers[typeof (T)] = handler;
}
}
public class IntAssetsHandler:Assets.IAssetHandler<int>
{
#region Implementation of IAssetHandler<out int>
public int GetAsset(string name)
{
return 0;
}
#endregion
}
static void Main(string[] args)
{
Assets.RegisterAssetHandler(new IntAssetsHandler());
Console.WriteLine(Assets.GetAsset<int>("test"));
}
您可以使用外部類,根據需要設置屬性類型,然后在函數中使用它。
public class MultipleOpjects
{
public List<string> ObjectOne { get; set; }
public List<object> ObjectTwo { get; set; }
public object ObjectThree { get; set; }
}
public MultipleOpjects GetAnything()
{
MultipleOpjects Vrble = new MultipleOpjects();
Vrble.ObjectOne = SomeThing1;
Vrble.ObjectTwo = SomeThing2;
Vrble.ObjectThree = SomeThing3;
return Vrble;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.