能否在插值字符串中嵌入函数?若可以,具体实现方式是什么?
Absolutely! In C# (which your code snippet uses), interpolated strings (prefixed with $) let you drop any valid C# expression right inside those curly braces {}—that includes function calls, method invocations, even quick conditional logic. No need to store every value in a separate variable first if you don't want to.
Here's how to apply this to your code
Your current code fetches multiple cell values and converts each to a string individually. Instead of assigning each to a variable, you can plug those Convert.ToString(VtlDxGrid.GetCellValue(...)) calls directly into an interpolated string to build your final output (like a full address, for example).
Your original approach (abbreviated):
foreach (var row in VtlDxGrid.GetSelectedRowHandles()) { string name = Convert.ToString(VtlDxGrid.GetCellValue(row, "ContactName")); string hn = Convert.ToString(VtlDxGrid.GetCellValue(row, "HouseName")); string street1 = Convert.ToString(VtlDxGrid.GetCellValue(row, "StreetLine1")); // ... more variables for other fields }
Refactored with embedded functions:
Let's say you want to combine all these into a single address string. You can do this in one formatted block without intermediate variables:
foreach (var row in VtlDxGrid.GetSelectedRowHandles()) { string fullAddress = $@" Contact Name: {Convert.ToString(VtlDxGrid.GetCellValue(row, ""ContactName""))} House Name: {Convert.ToString(VtlDxGrid.GetCellValue(row, ""HouseName""))} Street 1: {Convert.ToString(VtlDxGrid.GetCellValue(row, ""StreetLine1""))} Street 2: {Convert.ToString(VtlDxGrid.GetCellValue(row, ""StreetLine2""))} Town: {Convert.ToString(VtlDxGrid.GetCellValue(row, ""PostalTown""))} Postal Code: {Convert.ToString(VtlDxGrid.GetCellValue(row, ""PostalCode""))}"; // Use fullAddress however you need—print it, save it, etc. }
Quick tips for using this:
- Escape quotes properly: If you're using a verbatim interpolated string (
$@to preserve line breaks), double up quotes ("") inside the string (like for your column names). If you don't need line breaks, skip the@and use single quotes for column names if your API accepts them. - Add fallbacks easily: You can even include logic inside the braces, like handling null values. For example:
$"Street 2: {Convert.ToString(VtlDxGrid.GetCellValue(row, ""StreetLine2"")) ?? ""No second street""}" - Readability first: If you're using the same function call multiple times (like
GetCellValuehere), it's still okay to store repeated values in variables if that makes your code easier to scan. But embedding calls directly is totally valid for one-off uses.
This approach cleans up your code by cutting down on unnecessary variables and keeping all string construction logic in one place.
内容的提问来源于stack exchange,提问作者Dom Sinclair

