'System.DateTime'不是有效的Windows运行时参数类型

时间:2012-12-08 15:05:43

标签: c# windows-runtime windows-store-apps

我正在使用C#类,它在我的Windows应用商店应用程序(C#)中运行得非常好。但是当我尝试在Windows运行时Compenent中使用它时,我收到以下错误:

  

Calculator.Calculate(System.DateTime)'具有'System.DateTime'类型的参数'dateTime'。 “System.DateTime”不是有效的Windows运行时参数类型。

班级中的示例对象:

public DateTime Calculate(DateTime dateTime)
{
   int dayNumberOfDateTime = ExtractDayNumber(dateTime);
   int sunRiseInMinutes = CalculateSunRiseInternal(tanSunPosition, differenceSunAndLocalTime);
   return CreateDateTime(dateTime, sunRiseInMinutes);
}

我该如何解决这个问题?问题是什么?

2 个答案:

答案 0 :(得分:28)

创建Windows运行时组件时,您的组件可以被非托管语言使用,例如Javascript或C ++。显然,这些语言不知道如何生成适当的System.DateTime,它是一种特定的.NET类型。

因此,此类组件必须仅使用本机WinRT类型,否则将遵守WinRT中存在的限制。您将从一开始就遇到的一个限制是WinRT不支持实现继承。这要求您声明您的班级密封

本机WinRT类型与.NET类型非常不同。可以存储日期的实际运行时类型是Windows.Foundation.DateTime。字符串实际上是一个HSTRING句柄。 List实际上是一个IVector。等等。

毋庸置疑,如果您真的必须使用这些本机类型,那么您的程序就不再像.NET程序了。如果不这样做,CLR的.NET 4.5版本内置了语言投影。代码可以自动将WinRT类型转换为等效的.NET类型。那个翻译有一些粗糙的边缘,有些类型不容易被替换。但绝大多数人都没有遇到麻烦。

System.DateTime就是这样一个粗糙的边缘。 Windows.Foundation.DateTime的语言投影是System.DateTimeOffset。因此,只需通过声明您的方法来解决您的问题:

public DateTimeOffset Calculate(DateTimeOffset dateTime) {
    // etc..
}

值得注意的另一点是,只有其他代码可能使用的成员才需要这样做。公众成员。

答案 1 :(得分:1)

我的Windows运行时组件中也遇到了相同的问题,如下所示。

Severity Code Description Project File Line Suppression State
Error Method '.put_TxPower(System.SByte)' has parameter 'value' of type 'System.SByte'.  
System.SByte' is not a valid Windows Runtime parameter type.

正如Lukasz Madon在评论中提到的那样,将访问修饰符从公开更改为内部对我有用。

之前:

public sbyte TxPower { get; set; }

之后:

internal sbyte TxPower { get; set; }
相关问题