Console.ReadKey() 和 Console.ReadKey(Boolean)

本文详细介绍了在C#中使用Console类的ReadKey和ReadLine方法来接收用户输入的方式。包括如何使用Console.ReadKey()等待用户按键并选择性地显示按键,以及如何使用Console.ReadLine()等待用户输入一行文本。

Console.ReadKey()   获取用户按下的下一个字符或功能键。按下的键显示在控制台窗口中。

Console.ReadKey(Boolean)  获取用户按下的下一个字符或功能键。按下的键可以选择显示在控制台窗口中。

Console.ReadKey():

  1. static void Main(string[] args)
  2.         {
  3.             System.Console.WriteLine("Hello World!");
  4.             // Keep the console window open in debug mode.
  5.             System.Console.WriteLine("Press any key to exit.");
  6.             System.Console.ReadKey();
  7.         }

Console.ReadKey()等待用户按下键盘,输入任意键才退出程序,一次读入一个字符。为了使调试时看到输出结果。如果没有此句,命令窗口会一闪而过。.Console.ReadLine() 则会等待直到用户按下回车,一次读入一行。

Console.ReadKey(Boolean):

  1. [HostProtectionAttribute(SecurityAction.LinkDemand, UI = true)]
  2. public static ConsoleKeyInfo ReadKey(
  3.     bool intercept
  4. )
如果intercept 为False 则在控制台窗口中显示按下的键,为True则不显示。

// StorageUtil.ets import preferences from '@ohos.data.preferences'; import common from '@ohos.app.ability.common'; // 定义错误代码枚举 enum StorageErrorCode { PREFERENCES_GET_FAILED = 1001, DATA_SAVE_FAILED = 2001, DATA_READ_FAILED = 2002 } // 自定义存储错误类(使用明确类型) class StorageError extends Error { code: StorageErrorCode; operation: string; originalError: Error | null; // 避免使用 any constructor(code: StorageErrorCode, operation: string, message: string, originalError?: Error) { super(message); this.name = "StorageError"; this.code = code; this.operation = operation; this.originalError = originalError || null; Object.setPrototypeOf(this, StorageError.prototype); } } export class StorageUtil { private static readonly PREFERENCES_NAME: string = 'novelReaderPrefs'; private static readonly KEY_FONT_SIZE: string = 'fontSize'; private static readonly KEY_BRIGHTNESS: string = 'brightness'; private static readonly KEY_LAST_CHAPTER: string = 'lastChapter'; // 获取Preferences实例(使用明确返回类型) private static async getPreferences(context: common.UIAbilityContext): Promise<preferences.Preferences> { try { return await preferences.getPreferences(context, { name: StorageUtil.PREFERENCES_NAME }); } catch (error) { // 类型断言为Error const err = error as Error; console.error(`获取Preferences失败: ${err.message}`); // 使用自定义错误类型 throw new StorageError( StorageErrorCode.PREFERENCES_GET_FAILED, "getPreferences", "Preferences获取失败", err ); } } // 保存字体大小(明确参数类型) static async saveFontSize(context: common.UIAbilityContext, size: number): Promise<void> { try { const prefs = await StorageUtil.getPreferences(context); await prefs.put(StorageUtil.KEY_FONT_SIZE, size); await prefs.flush(); } catch (error) { // 类型检查 if (error instanceof StorageError) { console.error(`存储错误[${error.code}]: ${error.message}`); } else if (error instanceof Error) { console.error(`未知错误: ${error.message}`); } else { console.error("发生未知类型的错误"); } } } // 获取字体大小(明确返回类型) static getFontSize(context: common.UIAbilityContext): number { try { const prefs = preferences.getPreferencesSync(context, { name: StorageUtil.PREFERENCES_NAME }); // 使用类型安全的获取方式 const result: preferences.ValueType = prefs.getSync(StorageUtil.KEY_FONT_SIZE, 16); // 类型检查 if (typeof result === 'number') { return result; } else { console.warn("字体大小配置不是数字类型,使用默认值"); return 16; } } catch (error) { const err = error as Error; console.error(`获取字体大小失败: ${err.message}`); return 16; } } // 保存亮度(使用类型安全的API) static async saveBrightness(context: common.UIAbilityContext, value: number): Promise<void> { try { const prefs = await StorageUtil.getPreferences(context); await prefs.put(StorageUtil.KEY_BRIGHTNESS, value); await prefs.flush(); } catch (error) { const err = error as Error; console.error(`保存亮度失败: ${err.message}`); } } // 获取亮度(使用类型安全的获取) static getBrightness(context: common.UIAbilityContext): number { try { const prefs = preferences.getPreferencesSync(context, { name: StorageUtil.PREFERENCES_NAME }); const result: preferences.ValueType = prefs.getSync(StorageUtil.KEY_BRIGHTNESS, 50); if (typeof result === 'number') { return result; } else { console.warn("亮度配置不是数字类型,使用默认值"); return 50; } } catch (error) { const err = error as Error; console.error(`获取亮度失败: ${err.message}`); return 50; } } // 保存最后阅读章节(符合标准库使用规范) static async saveLastChapter(context: common.UIAbilityContext, chapter: number): Promise<void> { try { const prefs = await StorageUtil.getPreferences(context); await prefs.put(StorageUtil.KEY_LAST_CHAPTER, chapter); await prefs.flush(); } catch (error) { const err = error as Error; console.error(`保存章节失败: ${err.message}`); } } // 获取最后阅读章节(避免使用受限标准库) static getLastChapter(context: common.UIAbilityContext): number { try { const prefs = preferences.getPreferencesSync(context, { name: StorageUtil.PREFERENCES_NAME }); const result: preferences.ValueType = prefs.getSync(StorageUtil.KEY_LAST_CHAPTER, 1); if (typeof result === 'number') { return result; } else { console.warn("章节配置不是数字类型,使用默认值"); return 1; } } catch (error) { const err = error as Error; console.error(`获取章节失败: ${err.message}`); return 1; } } } 报错 Usage of standard library is restricted (arkts-limited-stdlib) <ArkTSCheck>,Prototype assignment is not supported (arkts-no-prototype-assignment) <ArkTSCheck>
06-27
import { GUIAgent } from '@ui-tars/sdk'; import { NutJSOperator } from '@ui-tars/operator-nut-js'; import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const config = { baseURL: 'https://ark.cn-beijing.volces.com/api/v3', apiKey: '3551f615-0e11-413d-8dd5-0736c0a9c1ce', model: 'doubao-1-5-ui-tars-250428', seed: 42, temperature: 0.1 }; const originalConsole = { log: console.log, info: console.info, error: console.error, warn: console.warn }; const filterGPTConversations = (data) => { if (data && data.conversations) { return data.conversations .filter(conv => conv.from === 'gpt') .map(conv => conv.value); } return data; }; const logger = { log: async (level, msg) => { const logMsg = `[${level.toUpperCase()}] ${new Date().toISOString()} - ${msg}\n`; originalConsole[level](logMsg); await fs.appendFile(path.resolve(__dirname, 'test.log'), logMsg); }, info: (msg) => logger.log('info', msg), error: (msg) => logger.log('error', msg), warn: (msg) => logger.log('warn', msg) }; console.log = (msg) => logger.log('info', msg); console.info = (msg) => logger.log('info', msg); console.error = (msg) => logger.log('error', msg); console.warn = (msg) => logger.log('warn', msg); async function loadTemplate(appName) { const template = await fs.readFile(path.resolve(__dirname, 'temp.txt'), 'utf8'); return template.replace(/\$\{appName\}/g, appName); } async function testApplication(appName) { if (!appName.trim()) return; await logger.info(`开始测试应用: ${appName}`); try { const testPrompt = await loadTemplate(appName); const operator = new NutJSOperator(); const agent = new GUIAgent({ operator, model: { ...config }, maxLoopCount: 50, loopIntervalInMs: 2000, onData: ({ data }) => { const gptMessages = filterGPTConversations(data); if (gptMessages.length){ logger.info(`UI-TARS: ${JSON.stringify(gptMessages)}`); } }, onError: ({ data, error }) => { logger.error(`ERROR: ${error}:${data}`); } }); await agent.run(testPrompt); await logger.info(`应用 ${appName} 测试完成`); } catch (err) { await logger.error(`应用 ${appName} 测试失败: ${err.message}`); } } async function runTests() { try { const appList = await fs.readFile(path.resolve(__dirname, 'appname.txt'), 'utf8'); const appNames = appList.split('\n').map(l => l.trim()).filter(Boolean); if (!appNames.length) throw new Error('未找到有效应用名'); await logger.info(`发现 ${appNames.length} 个应用,开始测试...`); for (const appName of appNames) await testApplication(appName); await logger.info(`测试完成,共测试 ${appNames.length} 个应用`); } catch (err) { await logger.error(`测试初始化失败: ${err.message}`); } } runTests(); 这个脚本能不能改成python的
最新发布
08-22
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值