并行数组索引失效:跨类传入公共方法的数组参数无法识别索引位置
Hey there! Let's break down the problem you're facing: when passing an array from another class into a public method, you can't access its index positions. This is a common snag, so let's walk through the most likely causes and fixes.
Common Causes & Solutions
1. The Array Isn't Properly Initialized
If you're passing a null array, or one that hasn't been allocated memory for elements, trying to access any index will throw an error. Always make sure the array is instantiated before passing it to the method.
Wrong:
// Only declaring the array, no memory allocated double[] extendedPrices; // Passing this to a method will cause issues when accessing indexes calculator.CalculatePrices(extendedPrices);
Right:
// Initialize the array with a fixed length double[] extendedPrices = new double[5]; // Or populate it directly double[] extendedPrices = { 10.99, 25.50, 5.75 };
2. Mismatched Parameter Types in the Public Method
Double-check that the public method's parameter is defined as an array (not a single variable or a different collection type like List<T>). If the method expects a different type, the compiler will flag it, or you'll get runtime errors when trying to use array indexes.
Wrong:
// Method expects a single double, not an array public void CalculatePrices(double extendedPrice) { // No index available here }
Right:
// Method correctly accepts a double array public void CalculatePrices(double[] extendedPrices) { // Now you can access indexes like extendedPrices[0] }
3. Index Out of Bounds
Even if the array is initialized, if you're trying to access an index that's equal to or larger than the array's Length, you'll get an IndexOutOfRangeException. Remember, arrays in C# are zero-indexed, so valid indexes range from 0 to array.Length - 1.
Example of a mistake:
double[] extendedPrices = new double[3]; // This will fail - index 3 is beyond the array's length (which is 3, indexes 0-2) extendedPrices[3] = 49.99;
4. Null Reference or Mismatched Array Lengths (For Multiple Arrays)
If you're passing multiple arrays to the method (like unit prices and quantities), ensure none are null and all have the same length. Mismatched lengths can lead to unexpected index errors when looping through them.
Example of a safe method check:
public void CalculateExtendedPrices(double[] unitPrices, int[] quantities, double[] extendedPrices) { // Guard clauses to catch issues early if (unitPrices == null || quantities == null || extendedPrices == null) { throw new ArgumentNullException("All arrays must be initialized"); } if (unitPrices.Length != quantities.Length || unitPrices.Length != extendedPrices.Length) { throw new ArgumentException("All arrays must have the same length"); } // Now safely access indexes for (int i = 0; i < unitPrices.Length; i++) { extendedPrices[i] = unitPrices[i] * quantities[i]; } }
Applying This to Your PricingApp Code
Looking at your PricingApp.cs snippet, you haven't added the array passing logic yet, but here's how you could integrate it smoothly:
class PricingApp { static void Main(string[] args) { DisplayTitle(); string productId; int unitQuantity; double unitPrice; string loopControl = "Y"; // Initialize arrays to store product data const int maxProducts = 5; double[] unitPrices = new double[maxProducts]; int[] quantities = new int[maxProducts]; double[] extendedPrices = new double[maxProducts]; int currentIndex = 0; while (loopControl.Equals("Y", StringComparison.OrdinalIgnoreCase) && currentIndex < maxProducts) { // Collect input from user Console.Write("Enter product ID: "); productId = Console.ReadLine(); Console.Write("Enter unit quantity: "); unitQuantity = int.Parse(Console.ReadLine()); Console.Write("Enter unit price: "); unitPrice = double.Parse(Console.ReadLine()); // Store data in arrays quantities[currentIndex] = unitQuantity; unitPrices[currentIndex] = unitPrice; // Call the public method from another class ProductCalculator calculator = new ProductCalculator(); calculator.CalculateExtendedPrices(unitPrices, quantities, extendedPrices); // Display the result Console.WriteLine($"Extended price: {extendedPrices[currentIndex]:C}"); // Update loop control Console.Write("Enter another product? (Y/N): "); loopControl = Console.ReadLine(); currentIndex++; } } static void DisplayTitle() { Console.WriteLine("=== Pricing Application ==="); } } // Example of the other class with the public method public class ProductCalculator { public void CalculateExtendedPrices(double[] unitPrices, int[] quantities, double[] extendedPrices) { if (unitPrices == null || quantities == null || extendedPrices == null) throw new ArgumentNullException("Arrays cannot be null"); for (int i = 0; i < unitPrices.Length; i++) { // Only calculate for indexes that have been populated if (i < quantities.Length && i < extendedPrices.Length) { extendedPrices[i] = unitPrices[i] * quantities[i]; } } } }
Start by verifying these key points in your code, and you should be able to resolve the index recognition issue.
内容的提问来源于stack exchange,提问作者user9677230

