在C#中,您可以做这样的事情吗?
type typeOfInt = type(int);
int x = (typeOfInt)1;
基本上,我想将类型存储为变量,因此可以将变量用作类型转换。我尝试这样做是因为在我的参数多态函数中,变量可能是2种类型中的1种。这两种类型都具有我想使用的相同方法,但是由于它属于变量类型,所以我不会使用它。
public static void SetFolderOrderValue<T>(T item, int value, Report reportObject)
{
if (!item.Exists)
{
reportObject.Log("The folder \"" + item.Name + "\" does not exist.");
return;
}
try
{
item.SetProperty(folderOrderProperty, value);
item.Update();
}
catch (SPException ex)
{
reportObject.Log("An error occurred when saving changes to the folder \"" + item.Name + "\". Maybe due to concurrent changes from another user. Please try again after a minute.\n" + Report.GetErrorInfo(ex));
}
catch (Exception ex)
{
reportObject.Log("An error occured with \"" + item.Name + "\":\n" + Report.GetErrorInfo(ex));
}
}
如果我至少可以将强制类型转换存储为值,那么我可以在函数中传递另一个布尔值,说明它是2种类型中的哪一种。
您正在谈论多态性,因此请使用它。
如果您有两种具有相同或通用方法的类型,并且有一个函数或一组函数要对其执行操作,请定义一个interface
描述这两种类型之间共享的方法集的,并:
如果你在谈论的类型命名SPFile
和SPFolder
public class SPFile : IMyNewInterface {
.....
}
public class SPFolder : IMyNewInterface {
...
}
public static void SetFolderOrderValue<T>(T item, int value,
Report reportObject) where T : IMyNewInterface {
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句