single-source 相关问题


根据单一条件改变几列

df <- data.frame(x=1:10) Can I mutate several columns based on a single condition? For example, I can do this: df %>% 变异(y = if_else(x>3,"Y","N"), z = if_else(x>...


GA4 配置发送浏览器标题而不是 CustomVirtualPageTitle

我已按照本指南中提到的步骤进行操作:https://www.analyticsmania.com/post/single-page-web-app-with-google-tag-manager/ 每当用户导航时 dataLayer.push 代码页面/st之间...


如何避免在微前端(Single-spa)应用程序中对 importmap.js 进行缓存

2 个微前端和根应用程序通过 AWS Cloudfront 分发部署在 S3 存储桶中。 在我的 s3 存储桶中,文件存储在以下结构中 app1_281(反应微前端) app2_13 ...


如何在Angular单元测试中正确获取子组件实例?

我正在 Angular 中用 karma 编写单元测试,但我正在努力解决奇怪的问题。我正在尝试测试 source-roll-history.dialog.ts 内部的 app-source-roll-history-form 的输出取消....


来自具有阻塞操作的迭代器的 Akka 源代码

Source.fromIterator 上的 Akka 文档 (https://doc.akka.io/docs/akka/current/stream/operators/Source/fromIterator.html) 说: 如果迭代器执行阻塞操作,请确保 r...


我该怎么做才能露出整个字符串?

真的很奇怪,当globalCompositeOperation为'source-atop'时它可以工作,但当globalCompositeOperation为''destination-atop'时却失败。看来不同类型的单词不能...


重新混合源映射支持 `TypeError: 列必须大于或等于 0,得到 -1`

使用bun和express运行remix,我遇到了source-map-support的错误。 使用 Express 中的代码 sourceMapSupport.install({ retrieveSourceMap:函数(源){ 控制台.log(


vim: ":source %" 命令导致错误 (E499)

如何解决此错误: E499: '%' 或 '#' 为空文件名,仅适用于“:p:h” 每当我在 vim 命令中使用 % 时都会发生此错误。我以前从未见过这个。这是我的 .vi...


使用 pip to source 安装 Python 包不会创建符号链接

所以我是 pip 和 virtualenv 的皈依者。我发现的一件事是,当我使用具有如下内容的requirements.txt时,后续的pip -E -rrequirements.txt的工作方式为


使用子目录制作给出“没有规则来制作目标...”

作为较大 makefile 的一部分,我使用 config.txt 和 perl 脚本从 .hh 文件创建 .h 文件。 .hh 文件位于 /source 目录中,生成的 .h 文件进入 /hdr 目录...


我的 R 脚本相同吗?

我认为这一定是重复的,但我似乎无法在堆栈上找到答案。有没有办法比较同一个 wd 中的两个 R 脚本,看看它们是否相同? 就像是: 一个<- source("


SSIS:如何设置与 SharePoint 文档的 oData Source 连接?

使用 SSIS,我必须从客户端放置的 SharePoint 网站中获取文件。这是两个文件,客户端每次需要处理新数据时都会简单地覆盖这些文件。该...


Maven:错误:-source 1.3 不支持泛型,我正在使用 1.6

我已将现有的 Maven 项目导入到 Eclipse IDE 中。 我修改了其中的一些代码,它编译成功了, 我使用 Java 1.6 作为编译器 当我尝试运行 Maven clean


如何解决从Linux在R 3.6.0中安装“udunits2”时出现“错误:libudunits2.a未找到”的问题?

我尝试使用以下命令在Linux中安装udunits2(因为我需要sf包): install.packages("/panfs/roc/groups/5/.../udunits2_0.13.tar.gz", repos=NULL, type ="source") 但我得到了这个电子...


不要对SQL Server中函数的结果集进行排序

我在 SQL Server 中有一个名为 source 的表,其中 source_id 作为主键,source_name 作为主键。 这是我的函数,它生成了错误的结果。 这是使用以下函数的插入语句: 我...


vim: ":source %" 命令导致错误: E499: '%' 或 '#' 的文件名为空,仅适用于 ":p:h"

如何解决此错误: E499: '%' 或 '#' 为空文件名,仅适用于“:p:h” 每当我在 vim 命令中使用 % 时都会发生此错误。我以前从未见过这个。这是我的 .vi...


AutoMapper 与 ConstructUsing 映射子属性在测试中无效,但在生产中有效

我正在尝试在我们的项目中测试 AutoMapper 配置文件的使用情况。我有一个对象 Source,我将其映射到 Destination,实际上它有大约 30 个属性,但对于这个例子来说它将是 fin...


如何在React Native中显示图像的顶部,

这是我现在的情况,我的形象是这样的 这是我当前的代码 这是我现在的情况,我的形象是这样的 这是我当前的代码 <View> <Image style={{width: '100%', height: 285}} source={{ uri: `${posterPath + data?.poster_path}`, }} resizeMode="cover" /> <Text>{data?.title}</Text> </View> 我希望我的图像看起来像这样 (这只是一个例子) 我知道在普通的CSS中我们是否可以使用object-position,但不幸的是React Native并不直接支持object-positionCSS属性,所以我很困惑如何实现这个 您需要使用 Flex:1,它使用整个屏幕,然后相应地定位和调整图像大小。 <View style={{flex:1}}> <Image style={{width:'100%', height:285}} source={{ uri: `${posterPath + data?.poster_path}`, }} resizeMode="cover" /> <Text>{data?.title}</Text> </View>


检测具有委托的元素内部的单击以及何时通过其类名称选择该元素

如何检测单击是否位于其侦听器被类选择的元素内部? 例如,我有一些类名为“my-class”的元素: 如何检测单击是否位于其侦听器被类选择的元素内部? 例如,我有一些类名为“my-class”的元素: <div class="my-class"> <button>Hello</button> <p>World</p> </div> <div class="my-class"> <a href="">Click</a> <a href="">Here</a> </div> 如果我只听课,点击内部元素是不行的: document.addEventListener("click", function(event) { if(event.target.classList.contains("my-class") { // } }); 我怎样才能检测到对其中任何元素的点击? 我发现了以下问题,但它仅适用于由 id 选择且没有委托的单个元素: Detect click inside/outside of element with single event handler 使用Element::closest()检查被点击的元素是在my-class内部还是my-class本身: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest document.addEventListener("click", function(event) { if(event.target.closest(".my-class")) { console.log('my-class clicked!'); } event.preventDefault(); }); <div class="my-class"> <button>Hello</button> <p>World</p> </div> <div class="my-class"> <a href="">Click</a> <a href="">Here</a> </div>


如何防止图片被下载到手机上?

假设这个标记: 假设这个标记: <picture> <source media="(max-width: 767px)" srcset="//placehold.it/350x150&text=Up+to+767" /> <source media="(max-width: 991px)" srcset="//placehold.it/350x150&text=Up+to+991" /> <img src="//placehold.it/570x200&text=Desktop+image" class="responsive-image" /> </picture> 是否可以在不使用 JavaScript 的情况下防止在小型设备上下载“最多 767”图像?虽然以下CSS将隐藏图像,并且似乎已经在视觉上解决了问题: @media (max-width: 767px) { .responsive-image { display: none; } } 它仍然会下载图像,这是我想避免的。我希望我可以简单地为我想要隐藏的图像提供一个空的 srcset 属性,但随后会加载下一个图像。 小提琴:https://jsfiddle.net/n68ousqu/ 我没有足够的声誉点来评论@MiscellaneousUser,但看来,至少在 Chrome 中,您可以从我原来的帖子中获取 HTML 和 CSS,然后只需将 loading="lazy" 添加到 img 元素即可获得这个工作。


ML.net - CreateTimeSeriesEngine

我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 列表 我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 List<RateData> infoList = new List<RateData>(); // populate list infoList = FileParser(infoList); IDataView data = mlContext.Data.LoadFromEnumerable<RateData>(infoList); 我设法像这样运行预测估计器 var forecastEstimator = mlContext.Forecasting.ForecastBySsa( outputColumnName: nameof(RatePrediction.CurrentRate), inputColumnName: nameof(RateData.HistoricalRate), windowSize: 14, seriesLength: numRateDataPoints, trainSize: numRateDataPoints, horizon: 1, confidenceLevel: 0.95f ); SsaForecastingTransformer forecaster = forecastEstimator.Fit(RateDataSeries); 然后我尝试创建这样的预测引擎 var ForecastEngine = Forecaster.CreateTimeSeriesEngine(mlContext); 这里我遇到了一些错误。 我的输入和输出类如下: public class RateData { public DateTime TransactionDate { get; set; } public float HistoricalRate { get; set; } } public class RatePrediction { public float CurrentRate; } 我有这样的错误 System.InvalidOperationException: Can't bind the IDataView column 'CurrentRate' of type 'Vector<Single, 1>' to field or property 'CurrentRate' of type 'System.Single'. at Microsoft.ML.Data.TypedCursorable`1..ctor(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, InternalSchemaDefinition schemaDefn) at Microsoft.ML.Data.TypedCursorable`1.Create(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, SchemaDefinition schemaDefinition) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2.PredictionEngineCore(IHostEnvironment env, InputRow`1 inputRow, IRowToRowMapper mapper, Boolean ignoreMissingColumns, SchemaDefinition outputSchemaDefinition, Action& disposer, IRowReadableAs`1& outputRow) at Microsoft.ML.PredictionEngineBase`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition, Boolean ownsTransformer) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at Microsoft.ML.Transforms.TimeSeries.PredictionFunctionExtensions.CreateTimeSeriesEngine[TSrc,TDst](ITransformer transformer, IHostEnvironment env, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at USD_EURO_Conversion_rate.TimeSeriesModelHelper.FitAndSaveModel(MLContext mlContext, IDataView RateDataSeries, String outputModelPath) 预测类中的属性需要是float[]类型;向量/数组而不是单个值,例如 public class RatePrediction { public float[] CurrentRate; } 类似于此处的Microsoft 示例。


如何在 C++/WinRT (WinUI3) 中将图像从内存读取到 ImageSource?

[1] 我想在 XAML 中显示 Image 控件的图像,但该图像来自字节数组。 我应该怎么办?图像格式可以是JPG、BMP或PNG之一。 [1] 我想在 XAML 中显示 Image 控件的图像,但该图像来自字节数组。 我该怎么办?图像格式可以是 JPG、BMP 或 PNG 之一。 <Image x:Name="img"/> void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data img().Source(???); // what should I do? } [2] 我尝试了InMemoryRandomAccessStream,但没有成功。 我知道在C#中使用MemoryStream很方便,但是如何在C++中实现它? 另一个问题是这个方法是否也适用于JPG和PNG格式的图像? void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data winrt::Microsoft::UI::Xaml::Media::Imaging::BitmapImage bmp; winrt::Windows::Storage::Streams::InMemoryRandomAccessStream stream; // How to read data from stream? bmp.SetSource(stream); img().Source(bmp); } [3] 现在功能已经实现了,但是还有两个问题 IAsyncAction MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data winrt::Microsoft::UI::Xaml::Media::Imaging::BitmapImage bmp; winrt::Windows::Storage::Streams::InMemoryRandomAccessStream stream; winrt::Windows::Storage::Streams::DataWriter dw(st.GetOutputStreamAt(0ULL)); dw.WriteBytes({ buf, size }); // This is very inefficient! co_await dw.StoreAsync(); dw.Close(); bmp.SetSource(stream); img().Source(bmp); stream.Close(); } 首先,我发现DataWriter::WriteBytes()确实是在复制数据。但我认为ImageSource只需要从我的buf中读取即可,不需要在读取之前将整个图像完全复制到流中。也许是类似MemoryView的东西,我这样想是不是错了? 其次,DataWriter和InMemoryRandomAccessStream的Close()应该在哪里调用? BitmapImage需要释放内存吗?这里有一个异步函数,我不知道应该写在哪里 [4] 根据IInspectable,我尝试了SHCreatMemStream并搜索了大量信息以提出另一个解决方案。目前的问题是,与方法[3]同样可行,但仍然会出现内存分配问题。 #include "Shlwapi.h" #include "shcore.h" #pragma comment(lib, "shlwapi.lib") void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data winrt::Microsoft::UI::Xaml::Media::Imaging::BitmapImage bmp; IStream* stream{ SHCreateMemStream(buf, size) }; // Copying takes a lot of time static const GUID guidIRandomAccessStream = { 0x905a0fe1, 0xbc53, 0x11df, { 0x8c, 0x49, 0x00, 0x1e, 0x4f, 0xc6, 0x86, 0xda } }; winrt::Windows::Storage::Streams::IRandomAccessStream pRas{ }; CreateRandomAccessStreamOverStream(stream, BSOS_OPTIONS::BSOS_DEFAULT, guidIRandomAccessStream, (void**)&pRas); bmp.SetSource(stream); img().Source(bmp); } 通过性能测试,发现CreateRandomAccessStreamOverStream的时间是一致的,但是SHCreateMemStream消耗的时间与图像大小成正比。可以得出,SHCreateMemStream中创建流的过程也涉及到内存的复制。 我对Windows编程中的Stream不是特别熟悉。创建流的过程一定会涉及到内存复制吗?从内存加载图像可以避免额外的开销吗?还有没有类似MemoryStreamView的结构来替代吗? 还有一个问题,我知道新的图像肯定需要内存存储。 BitmapImage设置Stream为Source会接管Stream占用的内存吗? Image控件设置BitmapImage作为Source会接管BitmapImage占用的内存吗? 如果是这样的话,我可以接受Stream分配新的内存,否则仍然是一个效率问题。 谢谢!!!!!!! 使用Stream已经彻底解决了这个问题。如前四期所述。 至于附加问题: ★1 使用 CreatStreamOnHGlobal 而不是 SHCreatMemStream。 因为SHCreatMemStream在调用过程中会对传入的内存块参数进行另一次内存复制。 CreatStreamOnHGlobal 创建流后不执行内存复制。您可以先通过GlobalAlloc分配内存,写入所需的图像数据,然后调用CreatStreamOnHGlobal,无需任何时间开销。另外,可以将CreatStreamOnHGlobal的第二个参数设置为true,自动释放GlobalAlloc分配的内存。 通过进程内存监控,我发现对于同一个程序,使用CreatStreamOnHGlobal的速度是SHCreatMemStream的两倍,并且不会导致内存泄漏。 ★2 创建的Stream需要调用Release方法减少一个引用。 IRandomAccessStream作为局部变量,会自动析构,无需主动释放。 并且BitmapImage还管理一部分引用,这些引用在离开作用域后被释放。 通过测试COM对象上Release方法的返回值,发现整个程序结束后引用计数又回到了0


内置布尔到可见性转换器无法编译

我正在尝试使用自动 IReference 到可见性转换将可见性绑定到 ToggleButton::IsChecked 我正在尝试使用自动 IReference 到可见性转换将可见性绑定到 ToggleButton::IsChecked <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"> <CheckBox x:Name="myButton" Content="Click Me" /> <TextBlock Text="Hello" Visibility="{x:Bind myButton.IsChecked, Mode=OneWay}"/> </StackPanel> 在空白项目中这是可行的。在我现有的项目中,如果我提供自己的转换器,它就会工作,但如果我尝试使用自动转换,我会得到: error C3779: 'winrt::impl::consume_Windows_Foundation_IReference< winrt::Windows::Foundation::IReference<bool>,T>::Value': a function that returns 'auto' cannot be used before it is defined with [ T=bool ] (compiling source file Generated Files\XamlTypeInfo.g.cpp) 如果针对 c++17 进行编译,错误就会消失。我正在为 c++20 编译 https://github.com/microsoft/microsoft-ui-xaml/issues/9214


如何在 Xamarin Forms 中缩放 WebView?

我无法缩放 Xamarin.Forms 中的 Web 视图。下面是代码,请有人帮助我。谢谢 我无法缩放 Xamarin.Forms 中的 Web 视图。下面是代码,请有人帮助我。谢谢你 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="highchart.MainPage"> <ScrollView> <WebView VerticalOptions="FillAndExpand" WidthRequest="80" HorizontalOptions="FillAndExpand"> <WebView.Source WebView.EnableZoomControls="true" WebView.ScalesPageToFit = "true"> <HtmlWebViewSource x:Name="HighChart"/> </WebView.Source> </WebView> </ScrollView> </ContentPage> 针对 Android 特定(在共享项目 [FORMS] 内) XAML 解决方案: <ContentPage ... xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"> <WebView Source="https://www.xamarin.com" android:WebView.EnableZoomControls="true" android:WebView.DisplayZoomControls="true" /> C# 解决方案: using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.AndroidSpecific; ... WebView.On<Android>().EnableZoomControls(true); WebView.On<Android>().DisplayZoomControls(true); 我在iOS上的Android上测试过,看来这个问题只出现在Android上。 您可以创建一个自定义渲染器来实现缩放功能,它在我这边工作得很好。 [assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))] namespace PDFPOC.Droid { public class CustomWebViewRenderer : WebViewRenderer { public CustomWebViewRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<WebView> e) { base.OnElementChanged(e); if (e.NewElement != null) { Control.Settings.AllowUniversalAccessFromFileURLs = true; Control.Settings.SetSupportZoom(true); Control.Settings.BuiltInZoomControls = true; Control.Settings.DisplayZoomControls = true; } } } }


NextJS 中 useFormStatus() 始终为 false

我尝试使用 useFormStatus() 在提交表单并等待获取数据时动态更改 UI。 我有一个像这样的表单组件 函数 onSubmit(数据:z.infer 我正在尝试使用 useFormStatus() 在提交表单并等待获取数据时动态更改 UI。 我有一个像这样的表单组件 function onSubmit(data: z.infer<typeof FormSchema>) { requestImg(data).then((imageStringify) => { const binaryData = Buffer.from(imageStringify.image); const imageBase64 = URL.createObjectURL( new Blob([binaryData.buffer], { type: "image/jpeg" } /* (1) */) ); setOpen(true); setSource(imageBase64); }); } if (isDesktop) { return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6" > ... 其中 requestImg(data) 是服务器操作。 然后,我将 Button 组件嵌套在不同的 Button.tsx 文件中的 <form> 中 import { useFormStatus } from "react-dom"; import { Button } from "@/components/ui/button"; export default function ButtonSub() { const { pending } = useFormStatus(); console.log(pending); return ( <Button className="w-full" type="submit" aria-disabled={pending}> {pending ? "Processing..." : "Submit"} </Button> ); } 问题是,当我单击提交时,按钮文本不会更改为“正在处理...” 编辑 似乎仅当您在表单上使用操作关键字时才有效。我试过了 <form action={async (formData: FormData) => { requestImg(formData).then((imageStringify) => { const binaryData = Buffer.from(imageStringify.image); const imageBase64 = URL.createObjectURL( new Blob([binaryData.buffer], { type: "image/jpeg" } /* (1) */) ); setSource(imageBase64); setOpen(true); }); }} className="w-2/3 space-y-6" > 但是现在使用 byte8Array 生成的图像已损坏。 我有一个带有动态 src 的图像,其中充满了 const [source, setSource] = useState(""); <img src={source}/> 似乎只有在您使用 action 关键字时才有效 形式。 确实如此。 useFormStatus 必须在表单的子组件内使用,它可以监视服务器操作的状态变化。但据我所知,它会监听 action。 action 定义提交后表单数据的服务器端目的地。在服务器操作的上下文中,服务器操作向当前 URL 发出 post 请求。所以它没有监听表单 onSubmit,这就是为什么你的第一个代码执行不起作用。 现在服务器操作在服务器上下文中运行,它们在服务器上执行,但setState是客户端特定的代码


MAUI 8 - 如何更改弹出背景叠加颜色?

使用 MAUI 7.0,下一个代码允许更改弹出背景叠加颜色,但该代码不适用于 MAUI 8.0 使用 MAUI 7.0,下一个代码允许更改弹出窗口背景覆盖颜色,但该代码不适用于 MAUI 8.0 <maui:MauiWinUIApplication x:Class="TestMaui8.WinUI.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:maui="using:Microsoft.Maui" xmlns:local="using:TestMaui8.WinUI"> <maui:MauiWinUIApplication.Resources> <Color x:Key="SystemAltMediumColor">Transparent</Color> <SolidColorBrush x:Key="SystemControlPageBackgroundMediumAltMediumBrush" Color="{StaticResource SystemAltMediumColor}" /> <SolidColorBrush x:Key="ContentDialogBackgroundThemeBrush" Color="{StaticResource SystemAltMediumColor}" /> <SolidColorBrush x:Key="ContentDialogDimmingThemeBrush" Color="{StaticResource SystemAltMediumColor}" /> <StaticResource x:Key="ContentDialogBackground" ResourceKey="SystemControlPageBackgroundMediumAltMediumBrush" /> <StaticResource x:Key="PopupLightDismissOverlayBackground" ResourceKey="SystemControlPageBackgroundMediumAltMediumBrush" /> <SolidColorBrush x:Key="SliderBorderBrush" Color="#1A73E8" /> <Style TargetType="Slider"> <Setter Property="BorderBrush" Value="{StaticResource SliderBorderBrush}"/> </Style> </maui:MauiWinUIApplication.Resources> </maui:MauiWinUIApplication> 有人知道为什么它不起作用以及如何修复它吗? 更新添加一些图片 CommunityToolkit Popup 没有 Overlay color 功能。您可以在 CommunityToolkit GitHub 页面上提出功能请求。 是的,您发布的上述代码曾经可以工作,但它不适用于具有最新 CommunityToolkit.Maui nuget 的 .NET8。 但是如果您想更改叠加颜色,这里有一个解决方法。 <toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui" ... Color="Black" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" > //make the size to be the full screen size <ContentView WidthRequest="1920" HeightRequest="1080"> <VerticalStackLayout WidthRequest="300" HeightRequest="300" BackgroundColor="Green"> <Image Source="dotnet_bot.png"/> <Label Text="Welcome to .NET MAUI!" VerticalOptions="Center" HorizontalOptions="Center" /> </VerticalStackLayout> </ContentView> </toolkit:Popup>


如何将 XAML(或另一个 ContentView)作为子项传递给 ContentView

我正在尝试创建一个 ContentView,并在其中将子项作为 XAML 或(另一个内容视图)传递。我怎样才能做到这一点? 例如。: 我有一种观点说 Header.xaml 我正在尝试创建一个 ContentView,并在其中将子项作为 XAML 或(另一个内容视图)传递。我怎样才能做到这一点? 例如: 我有一种观点是 Header.xaml <?xml version="1.0" encoding="utf-8" ?> <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:strings="clr-namespace:Eurynote.Localization.Resources.en;assembly=Eurynote.Localization" x:Class="Eurynote.Core.Views.Common.EurynoteHeader"> <HorizontalStackLayout Spacing="10" VerticalOptions="Center"> <Image Source="brand_icon" WidthRequest="32" HeightRequest="30" /> <Label Text="Header" Margin="0,-3,0,0" /> </HorizontalStackLayout> </ContentView> 现在,在我的 MainPage.xaml 文件中,我可以将此视图称为 <common:Header /> 并且运行良好。 但是我如何将另一个控件传递到与子项相同的内容视图,例如按钮、标签等...或任何其他 ContentView,如下面两个示例所示。 <common:Header> <Button Text="Button" /> </common:Header> <common:Header> <common:AnotherView /> </common:Header> 我想确保只能传递单个内容,如Frame。 谢谢你!!! 首先,如果使用以下代码,ContentView的内容将被Button覆盖。 <common:Header> <Button Text="Button" /> </common:Header> 因此您无法从 xaml 中为 contentview 添加子项。但你可以在后面的代码中做到这一点。如: 在xaml中: <common:Header x:Name = "header"> 在页面的构造函数中: public partial class MainPage() { InitializeComponent(); var layout = head.Content as HorizontalStackLayout; layout.Children.Add(new Button(){ Text = "new button"}); } 您可以通过这种方式将新项目作为子项添加到内容视图中。


ClosedXML 导出数据网格到 Excel 仅 10 行

我有一个包含 60 行数据的数据网格和一个将其导入 Excel 的按钮: 我有一个包含 60 行数据的数据网格和一个将其导入 Excel 的按钮: <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source}" CanUserAddRows="False" HeadersVisibility="All" Name="dgDisplay"> <DataGrid.Columns> <DataGridTextColumn Header="Day" Binding="{Binding Day}"/> <DataGridTextColumn Header="Data" Binding="{Binding Data}"/> </DataGrid.Columns> </DataGrid> <Button Command="{Binding SaveDataGridToExcelCommand}" CommandParameter="{Binding ElementName=dgDisplay}"/> 其中 Day 和 Data 只是一些随机生成的 int 数据。 我的代码使用 ClosedXML 将数据从中导出到 Excel,它使用 MainWindowViewModel: ObservableObject 调用 MVVM.Toolkit。 [RelayCommand] public void SaveDataGridToExcel(DataGrid dataGrid) { DataTable dt = new DataTable(); foreach (DataGridColumn column in dataGrid.Columns) { dt.Columns.Add(column.Header.ToString()); } foreach (var item in dataGrid.Items) { DataRow dr = dt.NewRow(); bool rowHasData = false; for (int i = 0; i < dataGrid.Columns.Count; i++) { var cellContent = dataGrid.Columns[i].GetCellContent(item); if (cellContent is TextBlock textBlock) { //check if row empty, dont add this row.I add it on purpose to check //if the datagrid recognite the rest 50 rows not have data. It actually //dont save those data dr[i] = textBlock.Text; if (!string.IsNullOrEmpty(textBlock.Text)) { rowHasData = true; } } } if (rowHasData) { dt.Rows.Add(dr); } } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Sheet1"); wb.SaveAs(saveFileDialog.FileName); } } } 但是保存的60行结果只显示了10行数据,其余50行都是空的。如果疑问为什么不使用Microsoft.Interop.Excel,那是因为该包不适合我的 Excel 版本。我没有在 ClosedXML 中看到任何对此有限制或许可的地方,所以我想知道为什么。如有任何帮助,我们将不胜感激。 在浏览 github 几个小时后,我自己找到了答案。 我没有访问单元格内容,而是直接从 DataGrid 的 ItemsSource 访问数据: public void SaveDataGridToExcel(DataGrid dataGrid) { DataTable dataTable = new DataTable(); foreach (DataGridColumn column in dataGrid.Columns) { dataTable.Columns.Add(column.Header.ToString()); } var itemsSource = dataGrid.ItemsSource as IEnumerable; if (itemsSource != null) { foreach (var item in itemsSource) { var properties = item.GetType().GetProperties(); var row = dataTable.NewRow(); foreach (var property in properties) { row[property.Name] = property.GetValue(item); } dataTable.Rows.Add(row); } } //show dialog... }


SecurityException:不允许启动服务Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (有额外功能)}

我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: 字符串SENDER_ID =“722*****53”; /** * 向 GCM 服务器异步注册应用程序。 * * 存储注册信息... 我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: String SENDER_ID = "722******53"; /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over // HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the // device will send // upstream messages to a server that echo back the message // using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } 我收到错误: 03-01 19:15:36.261: E/AndroidRuntime(3467): FATAL EXCEPTION: AsyncTask #1 03-01 19:15:36.261: E/AndroidRuntime(3467): java.lang.RuntimeException: An error occured while executing doInBackground() 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$3.done(AsyncTask.java:299) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.lang.Thread.run(Thread.java:841) 03-01 19:15:36.261: E/AndroidRuntime(3467): Caused by: java.lang.SecurityException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (has extras) } without permission com.google.android.c2dm.permission.RECEIVE 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startServiceAsUser(ContextImpl.java:1800) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startService(ContextImpl.java:1772) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.content.ContextWrapper.startService(ContextWrapper.java:480) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.b(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.register(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:177) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:1) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$2.call(AsyncTask.java:287) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 03-01 19:15:36.261: E/AndroidRuntime(3467): ... 4 more 这是我的清单: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.manyexampleapp" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> <uses-permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" /> <permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <application android:name="com.zoomer.ifs.BaseApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name="com.zoomer.ifs.MainActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|screenSize" android:launchMode="singleTop"> <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <!-- PUSH --> <!-- WakefulBroadcastReceiver that will receive intents from GCM services and hand them to the custom IntentService. The com.google.android.c2dm.permission.SEND permission is necessary so only GCM services can send data messages for the app. --> <receiver android:name="com.example.gcm.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <!-- Receives the actual messages. --> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.example.manyexampleapp" /> </intent-filter> </receiver> <service android:name="com.example.gcm.GcmIntentService" /> <activity android:name="com.example.gcm.DemoActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- DB --> <activity android:name="com.example.db.DbActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.http.RestGetActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > </activity> <activity android:name="com.example.fb.FacebookLoginActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SendFeedbackActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.zoomer.general.SearchNearbyOffersActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.manyexampleapp.StoresListActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb.ShareActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.notifications.NotificationsActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb2.no_use.MainActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.zoomer.offers.OffersListActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SearchNearbyOffersActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <service android:name="com.example.geo.LocationService" android:enabled="true" /> <receiver android:name="com.example.manyexampleapp.BootReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="com.example.manyexampleapp.LocationService.LOCATION_BROAD_MSG" /> </intent-filter> </receiver> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id" /> </application> </manifest> 改变 <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> 到 <!-- This app has permission to register and receive data message. --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 您收到异常是因为您尚未定义所需的权限 如果应用程序开发后安装了播放服务, 可能会发生 com.google.android.c2dm.permission.RECEIVE 权限已被授予但 android 仍在抱怨同样的错误。 在这种情况下,您必须完全重新安装开发的应用程序才能使此权限发挥作用。 我认为你必须检查 Kotlin 版本兼容性。


为什么现在无法播放 gdrive 文件中的音频?

我有这样的代码: 我有这样的代码: <audio id="player" autoplay controls> <source src="http://docs.google.com/uc?export=open&id=107VpNA7BU4AIxVsK2sRg69-rOigdU57n" type="audio/mp3"> </audio> 最初,上面的代码应该播放驱动器上文件中的歌曲。但是,由于某种原因,它不再起作用了。有人遇到过类似问题吗 听起来您面临着 HTML 的限制,不允许直接从 Google Drive 上的文件流式传输音乐。一种解决方法可能是将音乐文件托管在允许直接流式传输的服务器上,或者您可以考虑使用支持此功能的不同平台或技术。您需要帮助寻找替代解决方案或平台吗? Google 云端硬盘不支持直接流式传输。 您可以尝试使用 Dropbox OP的方法实际上确实适用于从谷歌驱动器传输音频,使用; src="http://docs.google.com/uc?export=open&id=file-id", 直到 2024 年 1 月 10 日左右。 在上述日期之前,我有几个 html/javascript 网络播放器直接从驱动器流式传输我的音乐。 Google 已开始推出影响第三方访问驱动器文件方式的更改;意思是在drive.google.com之外 来自 Google Drive 服务器之外的文件请求不再受到相同的处理。 下面链接中的答案部分解释了问题: https://stackoverflow.com/a/77805668/23238731 虽然这个答案是参考谷歌驱动器中的图像,但这同样适用于像OP代码一样链接的音频文件。 Google 建议用户现在使用 iframe 以 html 形式显示 google 云端硬盘内容,包括音频。 我已经对此进行了测试,iframe 选项确实适用于音频,尽管它对于流媒体没有用。


.NET MAUI:自定义Shell TitleView并绑定到当前页面标题

我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: 我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: <?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="MyNamespace.App.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyNamespace.App" xmlns:pages="clr-namespace:MyNamespace.App.Pages" BindingContext="{x:Static local:MainView.Instance}" Shell.FlyoutBehavior="{Binding ShellFlyoutType}" x:Name="shellMain"> <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" Text="{Binding Path=CurrentPage.Title, Mode=OneWay}" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> <ShellContent Title=" Login" ContentTemplate="{DataTemplate local:MainPage}" Route="login" FlyoutItemIsVisible="False" /> <ShellContent Title="Dashboard" ContentTemplate="{DataTemplate pages:DashboardPage}" Route="dashboard" /> </Shell> 我无法绑定当前页面标题。 我的 AppShell.xaml Shell 声明如下 <Shell ... x:Name="shellMain"> 作为替代方案,您可以在 OnNaviged 方法中设置 titleview : 在 AppShell.xaml 中,定义标签的名称 <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" x:Name="mylabel" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> 在AppShell.xaml.cs中,重写OnNaviged方法,获取当前项目 protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); var shellItem = Shell.Current?.CurrentItem; string title = shellItem?.Title; int iterationCount = 0; while (shellItem != null && title == null) { title = shellItem.Title; shellItem = shellItem.CurrentItem; if (iterationCount > 10) break; // max nesting reached iterationCount++; } myLabel.Text = title; } 希望它对你有用。 我正在尝试同样的方法来修改 TitleView 的外观。它可以在 iOS 上运行,尽管那里还有另一个错误。但在 Android 上我遇到了同样的问题。在前进导航中,它会更新标题,但当您按后退按钮时,标题不会更新。我已经打开了一个问题并添加了一个存储库。 https://github.com/dotnet/maui/issues/12416#issuecomment-1372627514 还有其他方法可以修改TitleView的外观吗? 我使用视图模型开发了这个解决方法,主要不是为了提供 MVVM 解决方案,而是因为其他建议的答案对我不起作用。 (我怀疑 Liqun Shen 2 月 15 日针对他自己的问题的评论中的建议会起作用。但我没有注意到这一点,直到我自己修复)。 当前页面的标题保存在可由 shell 的视图模型和每个内容页面的视图模型访问的类中: public class ServiceHelper { private static ServiceHelper? _default; public static ServiceHelper Default => _default ??= new ServiceHelper(); internal string CurrentPageTitle { get; set; } = string.Empty; } shell 中每个内容页面的视图模型提供其页面标题。为了促进这一点,大部分工作都是由基本视图模型完成的,它们都是从该模型派生而来的: public abstract class ViewModelBase(string title) : ObservableObject { private ServiceHelper? _serviceHelper; public string Title { get; } = title; internal ServiceHelper ServiceHelper { get => _serviceHelper ??= ServiceHelper.Default; set => _serviceHelper = value; // For unit testing. } public virtual void OnAppearing() { ServiceHelper.CurrentPageTitle = Title; } } 每个 shell 内容页面视图模型只需要让其基础视图模型知道它的标题: public class LocationsViewModel : ViewModelBase { public LocationsViewModel() : base("Locations") { } } 每个 shell 内容页面都需要在其视图模型中触发所需的事件响应方法: public partial class LocationsPage : ContentPage { private LocationsViewModel? _viewModel; public LocationsPage() { InitializeComponent(); } private LocationsViewModel ViewModel => _viewModel ??= (LocationsViewModel)BindingContext; protected override void OnAppearing() { base.OnAppearing(); ViewModel.OnAppearing(); } } Shell 的视图模型为标题栏提供当前页面的标题: public class AppShellViewModel() : ViewModelBase(Global.ApplicationTitle) { private string _currentPageTitle = string.Empty; public string CurrentPageTitle { get => _currentPageTitle; set { _currentPageTitle = value; OnPropertyChanged(); } } public void OnNavigated() { CurrentPageTitle = ServiceHelper.CurrentPageTitle; } } Shell 需要在其视图模型中触发所需的事件响应方法: public partial class AppShell : Shell { private AppShellViewModel? _viewModel; public AppShell() { InitializeComponent(); } private AppShellViewModel ViewModel => _viewModel ??= (AppShellViewModel)BindingContext; protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); ViewModel.OnNavigated(); } } 最后,Shell 的 XAML 在标题栏/导航栏上显示由 Shell 视图模型提供的当前页面的标题: <Shell.TitleView> <HorizontalStackLayout VerticalOptions="Fill"> <Image Source="falcon_svg_repo_com.png" HeightRequest="50"/> <Label x:Name="CurrentPageTitleLabel" Text="{Binding CurrentPageTitle}" FontSize="24" Margin="10,0" VerticalTextAlignment="Center"/> </HorizontalStackLayout> </Shell.TitleView>


在 C# 中将 Task<T> 转换为 Task<object>,无需 T

我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: 公共静态类 MyContextExtensions{ 公共静态异步任务 我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: public static class MyContextExtensions{ public static async Task<bool> SomeFunction(this DbContext myContext){ bool output = false; //...doing stuff with myContext return output; } public static async Task<List<string>> SomeOtherFunction(this DbContext myContext){ List<string> output = new List<string>(); //...doing stuff with myContext return output; } } 我的目标是能够从另一个类中的单个方法调用这些方法中的任何一个,并将其结果作为对象返回。它看起来像这样: public class MyHub: Hub{ public async Task<object> InvokeContextExtension(string methodName){ using(var context = new DbContext()){ //This fails because of invalid cast return await (Task<object>)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); } } } 问题是转换失败。我的困境是我无法将任何类型参数传递给“InvokeContextExtension”方法,因为它是 SignalR 中心的一部分并且由 javascript 调用。在某种程度上,我不关心扩展方法的返回类型,因为它只会序列化为 JSON 并发送回 javascript 客户端。但是,我确实必须将 Invoke 返回的值转换为任务才能使用等待运算符。我必须为该“任务”提供一个通用参数,否则它将把返回类型视为 void。因此,这一切都归结为如何成功地将具有通用参数 T 的任务转换为具有对象通用参数的任务,其中 T 表示扩展方法的输出。 您可以分两步完成 - await使用基类执行任务,然后使用反射或dynamic收获结果: using(var context = new DbContext()) { // Get the task Task task = (Task)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); // Make sure it runs to completion await task.ConfigureAwait(false); // Harvest the result return (object)((dynamic)task).Result; } 这是一个完整的运行示例,它将上述通过反射调用 Task 的技术置于上下文中: class MainClass { public static void Main(string[] args) { var t1 = Task.Run(async () => Console.WriteLine(await Bar("Foo1"))); var t2 = Task.Run(async () => Console.WriteLine(await Bar("Foo2"))); Task.WaitAll(t1, t2); } public static async Task<object> Bar(string name) { Task t = (Task)typeof(MainClass).GetMethod(name).Invoke(null, new object[] { "bar" }); await t.ConfigureAwait(false); return (object)((dynamic)t).Result; } public static Task<string> Foo1(string s) { return Task.FromResult("hello"); } public static Task<bool> Foo2(string s) { return Task.FromResult(true); } } 一般来说,要将 Task<T> 转换为 Task<object>,我会简单地采用简单的连续映射: Task<T> yourTaskT; // .... Task<object> yourTaskObject = yourTaskT.ContinueWith(t => (object) t.Result); (文档链接在这里) 但是,您实际的具体需求是 通过反射调用 Task 并获取其(未知类型)结果 。 为此,您可以参考完整的dasblinkenlight的答案,它应该适合您的具体问题。 我想提供一个实现,恕我直言,这是早期答案的最佳组合: 精确的参数处理 无动态调度 通用扩展方法 给你: /// <summary> /// Casts a <see cref="Task"/> to a <see cref="Task{TResult}"/>. /// This method will throw an <see cref="InvalidCastException"/> if the specified task /// returns a value which is not identity-convertible to <typeparamref name="T"/>. /// </summary> public static async Task<T> Cast<T>(this Task task) { if (task == null) throw new ArgumentNullException(nameof(task)); if (!task.GetType().IsGenericType || task.GetType().GetGenericTypeDefinition() != typeof(Task<>)) throw new ArgumentException("An argument of type 'System.Threading.Tasks.Task`1' was expected"); await task.ConfigureAwait(false); object result = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task); return (T)result; } 您不能将 Task<T> 转换为 Task<object>,因为 Task<T> 不是协变的(也不是逆变的)。最简单的解决方案是使用更多反射: var task = (Task) mi.Invoke (obj, null) ; var result = task.GetType ().GetProperty ("Result").GetValue (task) ; 这很慢且效率低下,但如果不经常执行此代码则可用。顺便说一句,如果您要阻塞等待其结果,那么异步 MakeMyClass1 方法有什么用呢? 另一种可能性是为此目的编写一个扩展方法: public static Task<object> Convert<T>(this Task<T> task) { TaskCompletionSource<object> res = new TaskCompletionSource<object>(); return task.ContinueWith(t => { if (t.IsCanceled) { res.TrySetCanceled(); } else if (t.IsFaulted) { res.TrySetException(t.Exception); } else { res.TrySetResult(t.Result); } return res.Task; } , TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } 它是非阻塞解决方案,将保留任务的原始状态/异常。 最有效的方法是自定义等待者: struct TaskCast<TSource, TDestination> where TSource : TDestination { readonly Task<TSource> task; public TaskCast(Task<TSource> task) { this.task = task; } public Awaiter GetAwaiter() => new Awaiter(task); public struct Awaiter : System.Runtime.CompilerServices.INotifyCompletion { System.Runtime.CompilerServices.TaskAwaiter<TSource> awaiter; public Awaiter(Task<TSource> task) { awaiter = task.GetAwaiter(); } public bool IsCompleted => awaiter.IsCompleted; public TDestination GetResult() => awaiter.GetResult(); public void OnCompleted(Action continuation) => awaiter.OnCompleted(continuation); } } 具有以下用法: Task<...> someTask = ...; await TaskCast<..., object>(someTask); 这种方法的局限性在于结果不是 Task<object> 而是一个可等待的对象。 我根据dasblinkenlight的回答做了一个小小的扩展方法: public static class TaskExtension { public async static Task<T> Cast<T>(this Task task) { if (!task.GetType().IsGenericType) throw new InvalidOperationException(); await task.ConfigureAwait(false); // Harvest the result. Ugly but works return (T)((dynamic)task).Result; } } 用途: Task<Foo> task = ... Task<object> = task.Cast<object>(); 这样您就可以将 T 中的 Task<T> 更改为您想要的任何内容。 对于最佳方法,不使用反射和动态丑陋语法,也不传递泛型类型。我将使用两种扩展方法来实现这个目标。 public static async Task<object> CastToObject<T>([NotNull] this Task<T> task) { return await task.ConfigureAwait(false); } public static async Task<TResult> Cast<TResult>([NotNull] this Task<object> task) { return (TResult) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.CastToObject().Cast<T2>(); 这是我的第二种方法,但不推荐: public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, TResult dummy = default) { return (TResult)(object) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.Cast((T2) default); // Or Task<T2> task2 = task.Cast<T1, T2>(); 这是我的第三种方法,但是不推荐:(类似于第二种) public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, Type<TResult> type = null) { return (TResult)(object) await task.ConfigureAwait(false); } // Dummy type class public class Type<T> { } public static class TypeExtension { public static Type<T> ToGeneric<T>(this T source) { return new Type<T>(); } } 用途: Task<T1> task ... Task<T2> task2 = task.Cast(typeof(T2).ToGeneric()); // Or Task<T2> task2 = task.Cast<T1, T2>(); 将 await 与动态/反射调用混合使用并不是一个好主意,因为 await 是一条编译器指令,它会围绕调用的方法生成大量代码,并且使用更多反射来“模拟”编译器工作并没有真正的意义,延续、包装等 因为您需要的是在运行时管理代码,然后忘记在编译时工作的 asyc await 语法糖。重写 SomeFunction 和 SomeOtherFunction 而不使用它们,并在运行时创建的您自己的任务中开始操作。您将得到相同的行为,但代码非常清晰。


© www.soinside.com 2019 - 2024. All rights reserved.